对非 Spring 应用程序使用 Artifactory 中的存根进行生产者契约测试
在此页面中,您将学习如何使用非 Spring 应用程序和上传到 Artifactory 的存根进行提供者契约测试。
流程
您可以阅读 开发您的第一个基于 Spring Cloud Contract 的应用程序 以了解使用 Nexus 或 Artifactory 中的存根进行提供者契约测试的流程。
设置消费者
对于消费者端,您可以使用 JUnit 规则。这样,您无需启动 Spring 上下文。以下列表显示了此类规则(在 JUnit4 和 JUnit 5 中);
- JUnit 4 规则
-
@Rule public StubRunnerRule rule = new StubRunnerRule() .downloadStub("com.example","artifact-id", "0.0.1") .repoRoot("git://[email protected]:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git") .stubsMode(StubRunnerProperties.StubsMode.REMOTE); - JUnit 5 扩展
-
@RegisterExtension public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension() .downloadStub("com.example","artifact-id", "0.0.1") .repoRoot("git://[email protected]:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git") .stubsMode(StubRunnerProperties.StubsMode.REMOTE);
设置生产者
默认情况下,Spring Cloud Contract 插件使用 Rest Assured 的 MockMvc 设置来生成测试。由于非 Spring 应用程序不使用 MockMvc,您可以将 testMode 更改为 EXPLICIT 以向绑定到特定端口的应用程序发送真实请求。
在此示例中,我们使用一个名为 Javalin 的框架来启动一个非 Spring HTTP 服务器。
假设我们有以下应用程序
import io.javalin.Javalin;
public class DemoApplication {
public static void main(String[] args) {
new DemoApplication().run(7000);
}
public Javalin start(int port) {
return Javalin.create().start(port);
}
public Javalin registerGet(Javalin app) {
return app.get("/", ctx -> ctx.result("Hello World"));
}
public Javalin run(int port) {
return registerGet(start(port));
}
}
给定该应用程序,我们可以设置插件以使用 EXPLICIT 模式(即,向真实端口发送请求),如下所示
- Maven
-
<plugin> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-contract-maven-plugin</artifactId> <version>${spring-cloud-contract.version}</version> <extensions>true</extensions> <configuration> <baseClassForTests>com.example.demo.BaseClass</baseClassForTests> <!-- This will setup the EXPLICIT mode for the tests --> <testMode>EXPLICIT</testMode> </configuration> </plugin> - Gradle
-
contracts { // This will setup the EXPLICIT mode for the tests testMode = "EXPLICIT" baseClassForTests = "com.example.demo.BaseClass" }
基类可能类似于以下内容
import io.javalin.Javalin;
import io.restassured.RestAssured;
import org.junit.After;
import org.junit.Before;
import org.springframework.cloud.test.TestSocketUtils;
public class BaseClass {
Javalin app;
@Before
public void setup() {
// pick a random port
int port = TestSocketUtils.findAvailableTcpPort();
// start the application at a random port
this.app = start(port);
// tell Rest Assured where the started application is
RestAssured.baseURI = "https://:" + port;
}
@After
public void close() {
// stop the server after each test
this.app.stop();
}
private Javalin start(int port) {
// reuse the production logic to start a server
return new DemoApplication().run(port);
}
}
通过这种设置
-
我们已将 Spring Cloud Contract 插件设置为使用
EXPLICIT模式发送真实请求而不是模拟请求。 -
我们定义了一个基类,它
-
为每个测试在随机端口上启动 HTTP 服务器。
-
将 Rest Assured 设置为向该端口发送请求。
-
在每个测试后关闭 HTTP 服务器。
-