In REST Assured, how can I check if a field is present or not in the response?

juliaaano picture juliaaano · Mar 27, 2017 · Viewed 28.5k times · Source

How can I make sure that my response, let's say it is in JSON, either contains or does not contain a specific field?

when()
    .get("/person/12345")
.then()
    .body("surname", isPresent()) // Doesn't work...
    .body("age", isNotPresent()); // ...But that's the idea.

I'm looking for a way to assert whether my JSON will contain or not the fields age and surname.

Answer

Luciano van der Veekens picture Luciano van der Veekens · Mar 27, 2017

You can use the Hamcrest matcher hasKey() (from org.hamcrest.Matchers class) on JSON strings as well.

when()
    .get("/person/12345")
.then()
    .body("$", hasKey("surname"))
    .body("$", not(hasKey("age")));