使用 Spring Cloud Contract 生成 Groovy DSL 契约
解读
在国内微服务面试中,Spring Cloud Contract 是验证“契约测试”落地能力的核心考点。面试官不仅想看你会不会写 Groovy DSL,更关注你能否把契约文件与 持续交付流水线、Gradle 多模块构建、Nexus 私服 结合,解决“Provider 与 Consumer 并行开发”这一典型痛点。因此,回答要体现:
- 契约文件放在 Git 仓库的 common-contract 模块,由 Provider 端维护;
- 使用 contractTest 任务生成 stub.jar 并发布到 Nexus 私服;
- Consumer 端通过 @AutoConfigureStubRunner 拉取最新 stub,实现本地测试;
- 通过 maven-publish 插件把契约版本与代码版本解耦,支持 灰度回滚。
知识点
- Groovy DSL 语法:request/response 块、regex、anyDate()、anyUuid() 等内置匹配器;
- Contract 文件命名规范:consumerName_providerName 格式,避免 stub 冲突;
- baseClassForTests:Provider 端需指定基类,负责 MockMvc 初始化与 @SpringBootTest 上下文;
- mappings/ 与 contracts/ 目录分离,保证 WireMock 映射 与 Groovy 源文件 隔离;
- CI 阶段顺序:contractTest → publishToMavenLocal → deploy 必须串行,防止 stub 未发布就被 Consumer 拉取;
- 多环境差异:使用 spring.cloud.contract.verifier.assert.skip 开关,在 预发环境 关闭校验,避免测试数据污染。
答案
步骤一:在 Provider 工程新建 src/contractTest/resources/contracts/order/createOrder.groovy
org.springframework.cloud.contract.spec.Contract.make {
request {
method 'POST'
url '/v1/orders'
headers {
contentType(applicationJson())
header 'X-Request-Id', anyUuid()
}
body([
skuId: $(regex('[0-9]{8}')),
qty : 1
])
}
response {
status 201
headers {
contentType(applicationJson())
header 'Location', ~'/v1/orders/[0-9]{16}'
}
body([
orderId: $(regex('[0-9]{16}')),
status : 'CREATED'
])
}
}
步骤二:Provider build.gradle(Groovy 语法)
plugins {
id 'org.springframework.cloud.contract' version '4.0.3'
id 'maven-publish'
}
ext {
set('springCloudVersion', "2022.0.3")
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
contracts {
baseClassForTests = 'com.example.OrderProviderBase'
testFramework = 'JUNIT5'
packageWithBaseClasses = 'com.example'
contractsDslDir = file("src/contractTest/resources/contracts")
}
publishing {
publications {
stubs(MavenPublication) {
artifactId = "${project.name}-stubs"
artifact contractVerifier.stubsJar
}
}
repositories {
maven {
url = uri("https://nexus.xxx.cn/repository/maven-releases/")
credentials {
username = findProperty('nexusUser')
password = findProperty('nexusPassword')
}
}
}
}
步骤三:Provider 基类 OrderProviderBase.groovy
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
abstract class OrderProviderBase extends Specification {
@Autowired
MockMvc mockMvc
@Autowired
OrderRepository orderRepository
def setup() {
// 数据初始化为空,防止测试污染
orderRepository.deleteAll()
}
}
步骤四:Consumer 端 build.gradle
dependencies {
testImplementation 'org.springframework.cloud:spring-cloud-starter-contract-stub-runner'
}
test {
useJUnitPlatform()
systemProperty 'spring.cloud.contract.stubrunner.repositoryRoot', 'https://nexus.xxx.cn/repository/maven-releases/'
systemProperty 'spring.cloud.contract.stubrunner.ids', 'com.example:order-service-stubs:1.0.0:stubs:8080'
}
步骤五:Consumer 测试
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@AutoConfigureStubRunner
class OrderConsumerSpec extends Specification {
@Autowired
private OrderClient orderClient
def "should create order via stub"() {
when:
def resp = orderClient.createOrder(new OrderRequest(skuId: '12345678', qty: 1))
then:
resp.orderId ==~ /[0-9]{16}/
resp.status == 'CREATED'
}
}
执行 ./gradlew contractTest publish 后,Nexus 出现 order-service-stubs-1.0.0.jar,Consumer 无需启动 Provider 即可通过 StubRunner 完成验证,实现 并行开发 与 回归防护。
拓展思考
- 契约版本漂移:在 feature 分支 阶段,Consumer 可覆盖 stubrunner.ids 为 +:latest.release,但 master 分支必须锁定版本,防止 线上回滚 时契约不一致;
- 性能压测:Groovy DSL 生成的 WireMock stub 仅支持 单线程模型,高并发场景需替换为 Testcontainers + 真实 Provider 实例;
- 契约即文档:通过 spring-cloud-contract-maven-plugin 的 generateDocs 目标,输出 Markdown 到 docs/ 目录,接入 语雀 或 Confluence,实现 测试即文档 的 DevOps 文化;
- 多协议支持:Spring Cloud Contract 4.x 已支持 WebFlux + RSocket,Groovy DSL 同样适用,但需注意 bodyMatchers 对 Flux 序列化的特殊处理;
- 合规审计:在 金融场景 下,契约文件需经过 SonarQube 自定义规则 扫描,禁止出现 硬编码手机号、身份证 等敏感数据,否则 CI 门禁 直接失败。