Reputation: 125
I have a question related to response body validation in Rest Assured. Let's suppose, I have such a response body as json.
{
"store": {
"books_count":3,
"books": [
{
"genre": "fiction",
"author": {
"name": "William",
"lastName" : "Evans"
}
},
{
"genre": "kids",
"author": {
"name": "Eric",
"lastName" : "Carle"
}
},
{
"genre": "science",
"author": {
"name": "Ronald",
"lastName" : "Forks"
}
}
]
}
}
I need to check:
the first assertion can be like:
response.body("store.books.genre", hasItem("kids);
But then I need to check if its author's name is William. Is there any way to check it using jsonPath?
I assume, that I can do deserialization (e.x. List<Book.class>, and then get an Author.class etc...), but is there any opportunity to check it with RestAssured. Thanks in advance!
Upvotes: 0
Views: 4412
Reputation: 1
Used jayway json path library
// Read your response Files.readAllBytes(Paths.get(System.getProperty("user.dir") + "/src/test/resources/myJson.json"));
// convert byte stream into string
String responseData =
new String(Files.readAllBytes(Paths.get(System.getProperty("user.dir") + "/src/test/resources/myJson.json")));
first part
List<String> genreList = JsonPath.parse(responseData).read("$..genre");
System.out.println(genreList.contains("kids"));// we can use assertions as well
Second part
List<Map<String, Object>> getAuthor = JsonPath.parse(responseData).read("$..[?( @['genre']=='kids')]");
Map<String, Object> title = (Map<String, Object>) getAuthor.get(0).get("author");
String author = (String) title.get("name");
System.out.println(author);
// assertEquals("Eric", author);
Upvotes: 0
Reputation: 5917
if a book of kids genre has autor name as Eric
You can leverage the GPath to extract value by condition
.body("store.books.find {it.genre == 'kids'}.author.name", is("Eric");
Upvotes: 1