How to verify that array contains object with rest assured?

yarafed picture yarafed · Mar 16, 2018 · Viewed 8.8k times · Source

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!

Answer

glytching picture glytching · Mar 16, 2018

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