Reputation: 370
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!
Upvotes: 21
Views: 28507
Reputation: 1
Could validate in single line by extracting using jsonpath()
assertTrue( response.then().extract().jsonPath()
.getList("$", Person.class)
.contains(person));
Upvotes: 0
Reputation: 137
This works for me:
body("path.to.array",
hasItem(
allOf(
hasEntry("firstName", "test"),
hasEntry("lastName", "test")
)
)
)
Upvotes: 12
Reputation: 47915
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));
Upvotes: 13
Reputation: 440
In this case, you can also use json schema validation. By using this we don't need to set individual rules for JSON elements.
Have a look at Rest assured schema validation
get("/products").then().assertThat().body(matchesJsonSchemaInClasspath("products-schema.json"));
Upvotes: 1