Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 211
juliaaano Avatar asked Mar 27 '17 11:03

juliaaano


People also ask

How do you validate response data in Rest assured?

We can verify the JSON response body using Assertions in Rest Assured. This is done with the help of the Hamcrest Assertion. It uses the Matcher class for Assertion. We shall send a GET request via Postman on a mock API, observe the Response.

How do you read a JSON response body using rest assured?

We can parse JSON Response with Rest Assured. To parse a JSON body, we shall use the JSONPath class and utilize the methods of this class to obtain the value of a specific attribute. We shall first send a GET request via Postman on a mock API URL and observe the Response body.


1 Answers

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")));
like image 111
Luciano van der Veekens Avatar answered Oct 10 '22 09:10

Luciano van der Veekens