For example, I have JSON in response:
[{"id":1,"name":"text"},{"id":2,"name":"text"}]}
I want to verify if a response contains a custom object. For example:
Person(id=1, name=text)
I found solution:
Person[] persons = response.as(Person[].class);
assertThat(person, IsArrayContaining.hasItemInArray(expectedPerson));
I want to have something like this:
response.then().assertThat().body(IsArrayContaining.hasItemInArray(object));
Is there any solution for this?
Thanks in advance for your help!
Check if Variable is Array ? Sometimes, you need to check a parsed JSON object or a variable to see if it's an array before iteration or before any other manipulation. You can use the Array. isArray method to check if a variable is an array.
To obtain JSON array size, we have to use the size method on the JSON array. Then introduce a loop that shall iterate up to the array size. We shall send a GET request via Postman on a mock API, and observe the Response. Using Rest Assured, let us get the value of the Location field having the values State and zip.
The body()
method accepts a path and a Hamcrest matcher (see the javadocs).
So, you could do this:
response.then().assertThat().body("$", customMatcher);
For example:
// 'expected' is the serialised form of your Person
// this is a crude way of creating that serialised form
// you'll probably use whatever JSON de/serialisaiotn library is in use in your project
Map<String, Object> expected = new HashMap<String, Object>();
expected.put("id", 1);
expected.put("name", "text");
response.then().assertThat().body("$", Matchers.hasItem(expected));
This works for me:
body("path.to.array",
hasItem(
allOf(
hasEntry("firstName", "test"),
hasEntry("lastName", "test")
)
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With