API Testing with Rest Assured - Validating the json schema


Sometimes you would get a json response while testing web applications. To make sure that all fields are present, but at the same time keeping the tests generic, you might write something like this given below.(although, a newbie way of writing tests)

 @Category(RegressionTests.class)
    @Test
    public void verifyResponseByValidatingPresenceOfAllFields() {
        given().
                param("product", "HomeLoan").
                param("fromHomeLoanId", -100).
        when().
                get("/loans").
        then().
                statusCode(200).
                contentType(ContentType.JSON).
                body(containsString("loans")).
                body(containsString("loanId")).
                body(containsString("businessId")).
                body(containsString("country")).
                body(containsString("statements")).
                body(containsString("statementId")).
                body(containsString("amount")).
                body(containsString("value")).
                body(containsString("refNo")).
                body(containsString("loanTypeId")).
                body(containsString("loanTypeDescription")).
                body(containsString("specialistComments")).
                body(containsString("analysis")).
                body(containsString("details")).
                body(containsString("originatingDD")).
                body(containsString("greatestLoanId"));
    }


The above test can be easily changed to a json schema validation.

@Category(RegressionTests.class)
    @Test
    public void verifyResponseByValidatingPresenceOfAllFields() {
        given().
                param("product", "HomeLoan").
                param("fromHomeLoanId", -100).
        when().
                get("/loans").
        then().
                statusCode(200).
                contentType(ContentType.JSON).
                assertThat().body(matchesJsonSchemaInClasspath("json-schemas/loans_schema.json"));
    }

The loans_schema.json is



For the method matchesJsonSchemaInClasspath to work, we need schema-validator to be used in our pom.


    io.rest-assured

json-schema-validator
3.0.7




Comments

Popular posts from this blog

The pesky scrollbars on Remote desktop - Finally fixed!!

Exploring RedCritter - website for Agile project mangement