How to verify that array contains object with rest assured?
Asked Answered
F

4

21

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!

Flanch answered 16/3, 2018 at 15:43 Comment(1)
Have you check their documentation on anonymous arrays github.com/rest-assured/rest-assured/wiki/…?Aspersorium
C
13

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));
Cardon answered 16/3, 2018 at 16:2 Comment(0)
S
13

This works for me:

body("path.to.array",
    hasItem(
          allOf(
              hasEntry("firstName", "test"),
              hasEntry("lastName", "test")
          )
    )
)
Spruce answered 9/6, 2020 at 9:13 Comment(2)
For me, I couldn't use the string directly and was forced to add equalTo() matcher in both strings ex: hasEntry(equalTo("firstName"), equalTo("test")).Hanshaw
Ended up here again with another tip, when value is not of the same type this approach does not work, use something like this instead. hasItem(both(hasEntry("firstName", "test")).and(hasEntry("age", 18)))Hanshaw
C
1

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"));
Cloris answered 19/3, 2018 at 8:57 Comment(2)
I use JSON schema for validation, but in the current case, I want to verify that array contains an object, it means that object value is important for me.Flanch
As far as I know - 'matchesJsonSchemaInClasspath' works with JSON Objects but does not work with JSON Arrays. If you know a straightforward way to make an array work with this I would love to check it out.Spermophyte
W
0

Could validate in single line by extracting using jsonpath()

    assertTrue( response.then().extract().jsonPath()
        .getList("$", Person.class)
        .contains(person));
    
Willamina answered 27/7, 2023 at 4:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.