如何使用RestAssured验证响应中的值列表?附JSON示例
嗨,我来帮你梳理下用RestAssured验证响应里的列表和列表项的方法,结合你给的书店JSON示例,咱们一步步来~
一、先做好基础准备
首先确保你已经引入了RestAssured的依赖(以Maven为例):
<dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>5.3.0</version> <scope>test</scope> </dependency>
然后发起请求拿到响应,比如:
Response response = given() .when() .get("你的接口URL") .then() .extract().response();
二、验证列表的整体属性
首先咱们可以先确认列表的基本信息,比如长度、字段集合这些:
- 验证列表长度:确认
book列表里有4本书given() .when() .get("你的接口URL") .then() .body("store.book.size()", equalTo(4)); - 验证所有元素的某个字段集合:比如确认所有书的作者包含指定的名字
given() .when() .get("你的接口URL") .then() .body("store.book.author", hasItems("Nigel Rees", "Herman Melville")); - 验证数值字段的范围:比如所有书的价格都不超过13
given() .when() .get("你的接口URL") .then() .body("store.book.price.every { it <= 13 }", is(true));
三、验证单个列表项的具体内容
针对列表里的某一项,咱们可以通过索引或者条件定位来验证:
- 通过索引定位验证:比如验证第一本书的标题和分类
given() .when() .get("你的接口URL") .then() .body("store.book[0].title", equalTo("Sayings of the Century")) .body("store.book[0].category", equalTo("reference")); - 通过条件过滤定位验证:比如找到分类为
fiction且作者是Evelyn Waugh的书,验证它的价格given() .when() .get("你的接口URL") .then() .body("store.book.find { it.category == 'fiction' && it.author == 'Evelyn Waugh' }.price", equalTo(12.99f)); - 验证字段是否存在:比如第三本书有
isbn字段,而其他书没有,咱们可以这样验证given() .when() .get("你的接口URL") .then() .body("store.book[2].isbn", notNullValue()) .body("store.book[0].isbn", nullValue());
四、进阶:批量验证列表项的规则
如果需要验证列表里的元素都符合某个规则,比如所有reference分类的书价格都低于10,可以这样写:
given() .when() .get("你的接口URL") .then() .body("store.book.findAll { it.category == 'reference' }.price.every { it < 10 }", is(true));
另外,也可以验证列表里是否存在符合某个条件的元素,比如存在标题包含Moby的书:
given() .when() .get("你的接口URL") .then() .body("store.book.any { it.title.contains('Moby') }", is(true));
内容的提问来源于stack exchange,提问作者Qaddaffi
相关产品推荐
相关产品推荐

