之前的文章已经举了一个http servlet的例子:
https://blog.youkuaiyun.com/xgw1010/article/details/144445321
本文在那基础上,举个webflux的例子,其中有些概念不重复说明,可以看上面的文章。
项目配置
plugins {
id "groovy"
id "org.springframework.cloud.contract" version "4.0.5"
id "maven-publish"
}
String contractVersion = "1.0.0-contract-SNAPSHOT"
ext {
set('springCloudVersion', "2022.0.5")
set('contractVersion', "4.0.5")
}
contracts {
testMode = 'WEBTESTCLIENT'
baseClassForTests = "com.leve.${artifactId}.ContractTestBase"
generatedTestJavaSourcesDir = project.file("src/contractTest/contract")
}
dependencies {
testImplementation("org.spockframework:spock-spring:${spockVersion}")
testImplementation("org.springframework.cloud:spring-cloud-starter-contract-verifier")
testImplementation("org.springframework.cloud:spring-cloud-starter-contract-stub-runner")
testImplementation("io.rest-assured:spring-web-test-client")
}
dependencyManagement {
imports {
mavenBom("org.springframework.cloud:spring-cloud-dependencies:${property("springCloudVersion")}")
mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${property("contractVersion")}"
}
}
publishing {
publications {
maven(MavenPublication) {
artifact(tasks.named('verifierStubsJar'))
}
// 如果项目名称带有横杠的,比如说auth-ghost,那么需要像下面这样去掉横杠,不然openfign404
// maven.artifactId = "authghost"
}
repositories {
maven {
url = uri("https://nexus.test.com/repository/leve-maven/")
version = contractVersion
credentials {
username = nexusUsername
password = nexusPassword
}
allowInsecureProtocol = false
}
}
}
基类
@SpringBootTest(properties = {
"spring.cloud.function.definition="
})
@AutoConfigureStubRunner
public class ContractTestBase{
@Autowired
private WebApplicationContext applicationContext;
@BeforeEach
public void setUp() {
RestAssuredWebTestClient.webAppContextSetup(applicationContext);
}
}
消费者配置
bootstrap.yaml
stubrunner:
ids:
- "com.leve:user"
- "com.leve:ghost"
repositoryRoot: https://nexus.leve.com/repository/leve-maven/
stubsMode: REMOTE
测试类上面使用 @AutoConfigureStubRunner
web flux 和web mvc 配置差异
web flux跟web mvc 相比主要是在
-
web flux : testMode = ‘WEBTESTCLIENT’
web mvc : testMode = ‘MockMvc’
-
web flux 另外添加 testImplementation(“io.rest-assured:spring-web-test-client”)
-
web flux : RestAssuredWebTestClient.webAppContextSetup(applicationContext);
web mvc: RestAssuredMockMvc.webAppContextSetup(applicationContext);