Skip to main content

JSON Schema Validation in REST Assured

Schema validation ensures that the response coming back from the endpoint matches with the predefined set of rules. So, without analyzing the response in detail, to know first-off whether the JSON body conforms to a certain JSON format. 

JsonSchemaValidator, A Hamcrest matcher that can be used to validate that a JSON document matches a given JSON schema. From version 2.1.0 REST Assured has support for Json Schema validation. 

Step 1: Add following dependency in pom.xml. You can check latest maven dependency from here.

<!-- https://mvnrepository.com/artifact/io.rest-assured/json-schema-validator -->
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>4.3.2</version>
</dependency>

Step 2: Then we need schema for test, which is generally provided by the developer but if it is not you can generate schema from here using json response.

Step 3: Save generated schema to .json file.

Step 4: Paste below code

@Test(enabled=true)
public void jsonschematest()
{	
    given()
        .pathParam("id", id)
        .when()
            .get("/users/{id}")
        .then()
            .assertThat()
            .body(matchesJsonSchemaInClasspath("com/pb/rest/presentation/testschema.json"));			
}

Step 5: If you are getting error do static import:

io.restassured.module.jsv.JsonSchemaValidatorSettings.settings;

Video Tutorial: Rest assured json schema validator example

Submitted by tgoswami on November 17, 2020

Tarun has 11+ years of experience in Quality Assurance in different domains like Banking, E-commerce, Health and Education.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.