使用 REST Docs 和存根(Stubs)在 Nexus 或 Artifactory 中進行 Provider 合同測試
在此流程中,我們不使用 Spring Cloud Contract 外掛來生成測試和存根。我們編寫 Spring RESTDocs,並從中自動生成存根。最後,我們設定構建工具來打包存根並將其上傳到存根儲存站點——在本例中是 Nexus 或 Artifactory。
生產者流程
作為生產者,我們
-
編寫 API 的 RESTDocs 測試。
-
將 Spring Cloud Contract Stub Runner starter 新增到我們的構建中 (
spring-cloud-starter-contract-stub-runner
),如下所示- Maven
-
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-contract-stub-runner</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
- Gradle
-
dependencies { testImplementation 'org.springframework.cloud:spring-cloud-starter-contract-stub-runner' } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } }
-
我們設定構建工具來打包我們的存根,如下所示
- Maven
-
<!-- pom.xml --> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <id>stub</id> <phase>prepare-package</phase> <goals> <goal>single</goal> </goals> <inherited>false</inherited> <configuration> <attach>true</attach> <descriptors> ${basedir}/src/assembly/stub.xml </descriptors> </configuration> </execution> </executions> </plugin> </plugins> <!-- src/assembly/stub.xml --> <assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd"> <id>stubs</id> <formats> <format>jar</format> </formats> <includeBaseDirectory>false</includeBaseDirectory> <fileSets> <fileSet> <directory>${project.build.directory}/generated-snippets/stubs</directory> <outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/mappings</outputDirectory> <includes> <include>**/*</include> </includes> </fileSet> </fileSets> </assembly>
- Gradle
-
task stubsJar(type: Jar) { classifier = "stubs" into("META-INF/${project.group}/${project.name}/${project.version}/mappings") { include('**/*.*') from("${project.buildDir}/generated-snippets/stubs") } } // we need the tests to pass to build the stub jar stubsJar.dependsOn(test) bootJar.dependsOn(stubsJar)
現在,當我們執行測試時,存根會自動釋出和打包。
以下 UML 圖顯示了生產者流程

消費者流程
由於消費者流程不受用於生成存根的工具影響,您可以閱讀 開發您的第一個基於 Spring Cloud Contract 的應用 以瞭解使用 Nexus 或 Artifactory 中的存根進行 Provider 合同測試的消費者端流程。