Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify that array contains object with rest assured?

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!

like image 429
Yaryna Avatar asked Mar 16 '18 15:03

Yaryna


People also ask

How check if object is JSON array?

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.

How use JSON array in Rest assured?

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.


2 Answers

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));
like image 131
glytching Avatar answered Nov 15 '22 15:11

glytching


This works for me:

body("path.to.array",
    hasItem(
          allOf(
              hasEntry("firstName", "test"),
              hasEntry("lastName", "test")
          )
    )
)
like image 26
Andrii Avatar answered Nov 15 '22 13:11

Andrii