跳到主要内容

使用上下文路径

DeepSeek V3 中英对照 Working with Context Paths

Spring Cloud Contract 支持上下文路径。

important

要完全支持上下文路径,唯一需要的更改是在生产者端进行切换。同时,自动生成的测试必须使用显式模式。消费者端保持不变。为了使生成的测试通过,你必须使用显式模式。以下示例展示了如何将测试模式设置为 EXPLICIT:

<plugin>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
<version>${spring-cloud-contract.version}</version>
<extensions>true</extensions>
<configuration>
<testMode>EXPLICIT</testMode>
</configuration>
</plugin>
contracts {
testMode = 'EXPLICIT'
}

这样,你生成的测试就不会使用MockMvc。这意味着你生成了真实的请求,并且需要设置生成的测试基类以在真实的套接字上工作。

考虑以下合约:

org.springframework.cloud.contract.spec.Contract.make {
request {
method 'GET'
url '/my-context-path/url'
}
response {
status OK()
}
}

以下示例展示了如何设置基类和 RestAssured:

import io.restassured.RestAssured;
import org.junit.Before;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;

@SpringBootTest(classes = ContextPathTestingBaseClass.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ContextPathTestingBaseClass {

@LocalServerPort int port;

@Before
public void setup() {
RestAssured.baseURI = "http://localhost";
RestAssured.port = this.port;
}
}

如果你这样做:

  • 自动生成测试中的所有请求都会发送到包含上下文路径的真实端点(例如,/my-context-path/url)。

  • 您的合约反映了您拥有一个上下文路径。您生成的存根也包含该信息(例如,在存根中,您必须调用 /my-context-path/url)。