简体   繁体   中英

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM