简体   繁体   中英

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

Could someone please me understand how to validate a list of items from the response. Say the response looks something like below,

{  
   "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"
         }
      ]
   }
}

The element Book has four lists under it with different data, now if I want to validate the author name and the price sequentially (in a loop for instance) how can I achieve that..?

I usually convert the response into a Json document and then validate, but in this case, if I use the Json path "Store.book.author", out of the four lists from the response, which list would it refer to..? That's where my confusion is.

There is in-build method in rest assured which you can use to get all item of Array as List of map.

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

When using Rest Assured with BDD, you can try this out.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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