繁体   English   中英

如何使用 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”,它会引用哪个列表? 这就是我的困惑所在。

有一个放心的内置方法,您可以使用它来获取 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");

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM