SHILI:
org.springframework.cloud.contract.spec.Contract.make {
request {
method 'PUT'
url '/fraudcheck'
body("""
{
"clientId":"1234567890",
"loanAmount":99999
}
""")
headers {
header('Content-Type', 'application/vnd.fraud.v1+json')
}
}
response {
status 200
body("""
{
"fraudCheckStatus": "FRAUD",
"rejectionReason": "Amount too high"
}
""")
headers {
header('Content-Type': 'application/vnd.fraud.v1+json')
}
}
}
示例2:
org.springframework.cloud.contract.spec.Contract.make {
request {
method 'PUT'
url '/api/12'
headers {
header 'Content-Type': 'application/vnd.org.springframework.cloud.contract.verifier.twitter-places-analyzer.v1+json'
}
body '''
[{
"created_at": "Sat Jul 26 09:38:57 +0000 2014",
"id": 492967299297845248,
"id_str": "492967299297845248",
"text": "Gonna see you at Warsaw",
"place":
{
"attributes":{},
"bounding_box":
{
"coordinates":
[[
[-77.119759,38.791645],
[-76.909393,38.791645],
[-76.909393,38.995548],
[-77.119759,38.995548]
]],
"type":"Polygon"
},
"country":"United States",
"country_code":"US",
"full_name":"Washington, DC",
"id":"01fbe706f872cb32",
"name":"Washington",
"place_type":"city",
"url": "http://api.twitter.com/1/geo/id/01fbe706f872cb32.json"
}
}]
'''
}
response {
status OK()
}
}
示例3:GET请求带parameters参数:例如/product?id=537
import org.springframework.cloud.contract.spec.Contract Contract.make { //ignored() request { method 'GET' urlPath('/product') { queryParameters { parameter('id', 537) } } } response { status 200 body( ''' { "description": "Consumer Test verifies provider", "name": "Consumer Test", "type": "testing product" } ''' ) headers { header('Content-Type', 'application/json;charset=UTF-8') } } }
示例4:
package contracts
org.springframework.cloud.contract.spec.Contract.make {
request {
method 'GET'
url '/abc/def/serviceA?catalog=x'
body("")
}
response {
status 200
body(""
)
headers {
contentType(applicationJsonUtf8())
}
}
}
header:
headers {
header('Content-Type', 'application/json;charset=UTF-8')
header('myHeader', 'duan')
}
我个人还是比较倾向于使用yaml,主要还是因为yaml语法比较简单,同时,对于90%的契约,其实都是简单型契约,很少会遇到复杂的使用场景,如果你要写一个特别复杂的契约,可能你就需要好好想想如何简化这个契约了。
契约只要组成部分就是 request(method,url,body,headers),response(status,body),我们比较常用的方式是 将request的body和response的body定义成2个json文件,然后,使用fromFile方法直接引用。
groovy 写法
import org.springframework.cloud.contract.spec.Contract
Contract.make {
request {
method('PUT')
headers {
contentType(applicationJson())
}
body(file("request.json"))
url("/1")
}
response {
status OK()
body(file("response.json"))
headers {
contentType(textPlain())
}
}
}
yaml写法
request: method: GET url: /foo bodyFromFile: request.json response: status: 200 bodyFromFile: response.json
request.json
{ "status" : "REQUEST" }
response.json
{ "status" : "RESPONSE" }
https://www.jianshu.com/p/e3277824a10a