2

有人可以请我了解如何验证响应中的项目列表。假设响应如下所示,

{  
   "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”,则在响应的四个列表中,它会引用哪个列表..?这就是我的困惑所在。

4

2 回答 2

1

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

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");
于 2018-04-20T11:39:56.820 回答
0

将 Rest Assured 与 BDD 一起使用时,您可以尝试一下。

given()
.when()
    .get(API URL)
.then()
     .assertThat().body("store.book.author[0]", equalTo("Nigel Rees"));
于 2020-10-31T15:14:36.363 回答