Sunday 24 November 2019

Rest Assured: Validate Response body


Using ‘body’ method, we can validate response body.

For example, when you hit the API ‘http://localhost:8080/api/v1/employees/by-names?firstName=Gopi&lastName=Battu’, you will get below response.

[
    {
        "id": 7,
        "firstName": "Gopi",
        "lastName": "Battu"
    }
]

You can validate id, firstName and lastName of the employee using below snippet.

Example
given().param("firstName", "Gopi")
       .param("lastName", "Battu")
       .header("Accept", "application/json")
       .when()
       .get("api/v1/employees/by-names")
       .then()
       .assertThat()
            .statusCode(200).and()
            .contentType(ContentType.JSON).and()
            .body("[0].id", equalTo(7)).and()
            .body("[0].firstName", equalTo("Gopi")).and()
            .body("[0].lastName", equalTo("Battu"));

TestApp.java
package com.sample.app;

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

import org.junit.Test;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;

public class TestApp {

    @Test
    public void testApp() {
        RestAssured.baseURI = "http://localhost:8080";

        given().param("firstName", "Gopi").param("lastName", "Battu").header("Accept", "application/json").when()
                .get("api/v1/employees/by-names").then().assertThat().statusCode(200).and()
                .contentType(ContentType.JSON).and().body("[0].id", equalTo(7)).and()
                .body("[0].firstName", equalTo("Gopi")).and().body("[0].lastName", equalTo("Battu"));

    }

}

 ‘equalTo’ is a hamcrest matcher to validate the response. If you would like to know more about hamcrest, I would recommend you to go through my below post.




Previous                                                    Next                                                    Home

No comments:

Post a Comment