如何用Rest Assured验证JSON中指定键值对的产品是否存在?
解决Rest Assured中按名称+价格断言产品存在的问题
问题背景
接口返回的JSON响应格式如下:
{"products": [{"name": "toy1","price": 99},{"name": "toy2","price": 88},{"name": "toy3","price": 99}]}
需要根据名称和价格的组合判断指定产品是否存在,预期断言结果:
| name | price | isExist |
|---|---|---|
| toy1 | 99 | true |
| toy2 | 99 | false |
| toy2 | 88 | true |
| sometoy | 99 | false |
此前尝试过转Map列表(实现繁琐)、使用JsonPath包(受限无法使用)、扁平化JSON(出现键冲突),均未解决问题。
解决方案
直接利用Rest Assured自带的响应解析能力,结合Java Stream流操作实现,无需额外依赖:
代码实现
import io.restassured.response.Response; import java.util.List; import java.util.Map; // 假设已获取接口响应对象response Response response = ...; // 提取products列表 List<Map<String, Object>> productsList = response.jsonPath().getList("products"); // 判断产品是否存在的方法 public boolean isProductPresent(String targetName, int targetPrice) { return productsList.stream() .anyMatch(product -> targetName.equals(product.get("name")) && targetPrice == (int) product.get("price") ); } // 执行断言验证 assert isProductPresent("toy1", 99) == true; assert isProductPresent("toy2", 99) == false; assert isProductPresent("toy2", 88) == true; assert isProductPresent("sometoy", 99) == false;
方案说明
- 用Rest Assured内置的
jsonPath().getList()直接提取products数组为Map列表,省去手动解析JSON的冗余步骤 - 通过Stream的
anyMatch()方法,一次遍历即可完成名称+价格的组合匹配判断,代码简洁高效 - 无需引入额外依赖或做JSON扁平化处理,规避了之前遇到的键冲突、依赖受限等问题
内容的提问来源于stack exchange,提问作者shadowless
相关产品推荐
相关产品推荐

