如何使用Rest Assured IO JSONPath读取JSONArray节点并验证指定条件
使用REST Assured验证JSON数组中的特定元素
针对你给出的JSON数组响应,要验证是否存在name字段包含"Military"且amount字段等于500的项,我们可以利用REST Assured对Groovy表达式的支持,结合Hamcrest匹配器来实现精准断言。
首先,先回顾下你的接口返回的JSON结构:
[ { "incentiveId":11791331, "autoApplied":null, "name":"Toyota US Lease Loyalty - National excl. Southeast", "amount":500, "expirationDate":"2018-07-09", "minimumTerm":null, "maximumTerm":null, "groupAffiliation":null, "previousOwnership":"Lease Loyalty" }, { "incentiveId":11990139, "name":"Toyota US Military Appreciation - National excl. Southeast", "amount":1000, "expirationDate":"2018-12-31", "groupAffiliation":"Military", "previousOwnership":null } ]
接下来是具体的实现代码,核心是用Groovy的findAll闭包来筛选符合双条件的元素,再断言筛选结果不为空:
import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.*; public class IncentiveVerificationTest { public static void main(String[] args) { // 配置请求并发送 given() .baseUri("你的API基础地址") // 替换为实际的API地址 .header("Content-Type", "application/json") // 根据接口需求添加headers .when() .get("/你的接口路径") // 替换为实际的接口路径 .then() .statusCode(200) // 先验证接口返回状态码正常 // 核心断言:筛选出name含"Military"且amount=500的元素,断言结果非空 .body("findAll { it.name.contains('Military') && it.amount == 500 }", not(empty())); } }
代码说明:
- Groovy表达式
findAll:遍历JSON数组中的每一个元素(用it指代当前元素),同时检查两个条件:it.name.contains('Military'):当前元素的name字段包含"Military"字符串it.amount == 500:当前元素的amount字段值等于500
- Hamcrest匹配器
not(empty()):断言筛选出来的结果集合不为空,也就是存在至少一个符合条件的元素。
如果需要更严格的验证(比如确保只有一个符合条件的项),可以把not(empty())替换为hasSize(1):
.body("findAll { it.name.contains('Military') && it.amount == 500 }", hasSize(1));
这样就能精准验证你需要的条件啦!
内容的提问来源于stack exchange,提问作者Srinivasan Ramu
相关产品推荐
相关产品推荐

