文章目录
这里契约测试基于Spring Cloud Contract来编写,大致流程如下所示:
- 在Provider使用groovy DSL编写Contract
- 通过Contract Verifier验证Contract所生成的测试
- 测试通过后将Artifact(stub.jar)发布到Maven仓库中
- 在Consumer端pull下相应的Artifact(stub.jar)
- 运行测试,同时以Artifact作为基础设施启动Stub server
- 在测试中向Stub server发送请求验证API的正确性
Provider
添加gradle插件和依赖
buildscript {
ext {
springBootVersion = '2.0.5.RELEASE'
springColudContractVersion = '2.0.2.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
// ......
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("org.springframework.cloud:spring-cloud-contract-gradle-plugin:${springColudContractVersion}")
// ......
}
}
// ......
apply plugin: 'groovy'
apply plugin: 'spring-cloud-contract'
// ......
dependencies {
// ......
testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
// ......
}
编写Contract
按照Spring Cloud Contract的约定,groovy编写的DSL文件需要在在src/test/resources/contracts/目录下。
import org.springframework.cloud.contract.spec.Contract
Contract.make {
request {
url "/goods"
method GET()
}
response {
status 200
headers {
contentType applicationJson()
}
body '''
[{
"id" : 1,
"name" : "123",
},
{
"id" : 2,
"name" : "456",
},
{
"id" : 3,
"name" : "789",
}]
'''
}
}
创建测试基类
给从Contract生成的测试类指定一个基类。按照Spring Cloud Contract的约定基类以Base结尾。
@RunWith(SpringRunner.class)
@SpringBootTest