如何使用 RestAssured 验证响应中的值列表

How to validate a list of values from the response using RestAssured

有人能告诉我如何验证响应中的项目列表吗?假设响应如下所示,

{  
   "store":{  
      "book":[  
         {  
            "author":"Nigel Rees",
            "category":"reference",
            "price":8.95,
            "title":"Sayings of the Century"
         },
         {  
            "author":"Evelyn Waugh",
            "category":"fiction",
            "price":12.99,
            "title":"Sword of Honour"
         },
         {  
            "author":"Herman Melville",
            "category":"fiction",
            "isbn":"0-553-21311-3",
            "price":8.99,
            "title":"Moby Dick"
         },
         {  
            "author":"J. R. R. Tolkien",
            "category":"fiction",
            "isbn":"0-395-19395-8",
            "price":22.99,
            "title":"The Lord of the Rings"
         }
      ]
   }
}

元素 Book 下面有四个列表,其中包含不同的数据,现在如果我想按顺序(例如在一个循环中)验证作者姓名和价格,我该如何实现..?

我通常将响应转换成Json文档然后验证,但在这种情况下,如果我使用Json路径"Store.book.author",从响应,它指的是哪个列表..?这就是我的困惑所在。

放心,有in-build方法,你可以使用它来获取Array的所有项目作为地图的List。

String key="book";//array key (as it mentioned in your Json)
Response response=//your API call which will return Json Object
List<Hash<String,Object>>booksList=response.jsonPath().getList(key);
//Now parse value from List
Hash<String,Object> firstBookDetails=booksList.get(0);// for first index
String author=(String)firstBookDetails.get("author");

将 Rest Assured 与 BDD 结合使用时,您可以试试这个。

given()
.when()
    .get(API URL)
.then()
     .assertThat().body("store.book.author[0]", equalTo("Nigel Rees"));