juliaaano
juliaaano

Reputation: 1407

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.

Upvotes: 39

Views: 57944

Answers (5)

RedCrossEvvy
RedCrossEvvy

Reputation: 1

I had a similar problem where my response included a field or not depending on the result set. I found that you can use try/except to test the field (try) and if it isn't present then process the exception, which in my case, I just wanted to pass on it. One could write code in the except to correct the errant field if that suits the use case.

try:
   something = response.json['field_name']
except:
   pass

# For op's use case:
try:
   surname = response.json['surname']
except:
   surname = None   # or whatever you'd like to do with a missing surname.

Upvotes: -1

Luciano van der Veekens
Luciano van der Veekens

Reputation: 6577

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

Upvotes: 86

ForJaysSake
ForJaysSake

Reputation: 48

Using: import static org.junit.Assert.assertThat;

Your could then: assertThat(response.then().body(containsString("thingThatShouldntBeHere")), is(false));

Upvotes: -2

Marcin Tarka
Marcin Tarka

Reputation: 56

Check whetever field is null. For example:

    Response resp = given().contentType("application/json").body(requestDto).when().post("/url");
    ResponseDto response = resp.then().statusCode(200).as(ResponseDto.class);
    Assertions.assertThat(response.getField()).isNotNull();

Upvotes: 0

J. N
J. N

Reputation: 193

You can use equals(null) like this:

.body("surname", equals(null))

If the field does not exists it will be null

Upvotes: 0

Related Questions