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

时间:2018-04-19 11:08:39

标签: java automated-tests rest-assured rest-assured-jsonpath

有人可以让我了解如何验证回复中的项目列表。说响应看起来像下面的那样,

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

2 个答案:

答案 0 :(得分:1)

我们可以使用in-build方法将所有数组项作为地图列表。

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");

答案 1 :(得分:0)

在将Best Restured与BDD结合使用时,您可以尝试一下。

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