對非 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 伺服器。
-