![](/img/trans.png)
[英]Using Complex JSON in Spring Cloud Contract Groovy contract
[英]How can I get/print the JSON response from a RESTful service call in Groovy with Spring Cloud Contract
在实施Spring Cloud Contract以进行微服务的集成测试时,我已经在Groovy中定义了一个Contract,并通过将值硬编码到.json文件中来比较了预期的JSON响应。 一切正常。
但是,如果我想动态验证而不是拥有静态JSON响应,我找到了一种方法,但是我需要从REST端点调用的响应中将动态JSON响应转换为字符串变量。
import org.springframework.cloud.contract.spec.Contract
Contract.make {
request {
method 'GET'
url '/micro-service/90640454'
headers {
header 'Content-Type': 'application/json;charset=UTF-8'
}
}
response {
status 200
headers {
header 'Content-Type': 'application/json;charset=UTF-8'
}
-- how can i get the actual_response here
body (file('expected_response.json'))
}
}
在主体的响应侧提供execute
方法
import org.springframework.cloud.contract.spec.Contract
Contract.make {
request {
method 'GET'
url '/micro-service/90640454'
headers {
header 'Content-Type': 'application/json;charset=UTF-8'
}
}
response {
status 200
headers {
header 'Content-Type': 'application/json;charset=UTF-8'
}
-- how can i get the actual_response here
body ($(consumer(file('expected_response.json')), producer('assertMe($it)'))
}
}
然后在基类中,您必须在assertMe
方法中定义并执行断言。 像这样:
public void assertMe(Object o) { ... perform assertions ... }
如果您阅读文档( https://cloud.spring.io/spring-cloud-static/Finchley.SR2/single/spring-cloud.html#contract-matchers ),则会发现
从JSON读取的对象的类型可以是以下之一,具体取决于JSON路径:
字符串:如果您指向一个字符串值。 JSONArray:如果指向列表。 地图:如果您指向地图。 数字:如果您指向整数,双精度号或其他类型的数字。 布尔值:如果您指向布尔值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.