Verify if a field in a JSON response is not set with Rest Assured

Featured image for sharing metadata for article

Earlier today I was trying to write some assertions on a Rest Assured Response, where I was validating that the resulting JSON had fields that were not being returned.

Let us say that I want to validate that the response coming back does not have the field description, only id:

{
  "id": 1
}

To interact with a JSON Response, I used the .path method on the Response, such as:

import io.restassured.response.Response;

import static io.restassured.RestAssured.given;

Response response = given()
  .when()
  .get("...");
String description = response.path("description");
// assert with your favourite assertion library
assertThat(description).isNotNull();

This worked great until I realised that it wouldn't handle the case where description returns a null:

{
  "id": 1,
  "description": null
}

This means we instead need to use Rest Assured's ValidatableResponse and Hamcrest's hasKey matcher:

import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.hasKey;

// ...
Response response = given()
  .when()
  .get("...");
ValidatableResponse validatableResponse = response.then();
validatableResponse.body("$", not(hasKey("description")));

This will then throw an AssertionError when we have a description field present, even if it's set to null:

Exception in thread "main" java.lang.AssertionError: 1 expectation failed.
JSON path $ doesn't match.
Expected: not map containing ["description"->ANYTHING]
  Actual: {description=null, id=1}

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #java #rest-assured #json.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.