Getting and Verifying Response in Rest Assured – Part 8

What we have learned so far?

Part 1 – What is Rest Assured? How to setup Rest Assured?
https://www.onlyfullstack.com/what-is-rest-assured-how-to-setup-rest-assured/

Part 2 – Sample Rest API To Test With Rest Assured
https://www.onlyfullstack.com/sample-rest-api-to-test-with-rest-assured/

Part 3 – How to make a GET Request using Rest Assured – Only Fullstack
https://www.onlyfullstack.com/how-to-send-get-request-in-rest-assured/

Part 4 – How to make a POST Request using Rest Assured – Only Fullstack
https://www.onlyfullstack.com/how-to-send-post-request-in-rest-assured/

Part 5 – How to make a PUT Request using Rest Assured – Only Fullstack
https://www.onlyfullstack.com/how-to-send-put-request-in-rest-assured/

Part 5 – How to make a DELETE Request using Rest Assured – Only Fullstack
https://www.onlyfullstack.com/how-to-send-delete-request-in-rest-assured/

Part 7 – JsonPath and XmlPath in Response Rest Assured – Only Fullstack
https://www.onlyfullstack.com/jsonpath-and-xmlpath-in-rest-assured/

 

Different ways to Verify the Response in Rest Assured

we can verify the responses in different ways in Rest Assured. Lets explore the different ways and techniques to do so.

1. Verify Response with JsonPath in Rest Assured

We can use the JsonPath to verify the response. We can pass the JsonPath in the first parameter of the body method and the expected matcher in the second parameter.

@Test
public void validateWithJsonPath() {
    String requestEmployeeId = "2";
    RestAssured.given() //precondition is to give the base uri
            .baseUri("http://localhost:8088/")
            .pathParam("employee_id", requestEmployeeId)
            .when() //actual action is to perform the get request
            .get("employees/{employee_id}")
            .then() // will return the ValidatadleResponse from the Response object
            .statusCode(200)
            .header("Content-Type", "application/json;charset=UTF-8")
            .body("id", Matchers.equalTo(2)) // json path of a simple object
            .body("firstName", Matchers.equalTo("only"))
            .body("lastName", Matchers.equalTo("fullstack"))
            .body("salary", Matchers.equalTo(2000))
            .body("email", Matchers.equalTo("onlyfullstack@abc.com"));
}

2. Extracting the response and Validating with assertion

We can compare the response coming from the rest assured method and the expected response.
Note – Make sure you have override the equals method in your response class.

Here we are calling the extract method and providing the datatype in which we want to convert the json. We got the Employee object from rest assured get call and stored into the actualResponse and now we can compare the actualResponse and expectedResponse with assertEquals method.

@Test
public void validateWithExtractedObject() {
    String requestEmployeeId = "2";
    Employee expectedResponse = new Employee(2, "only", "fullstack", 2000, "onlyfullstack@abc.com");

    Employee actualResponse = RestAssured.given() //precondition is to give the base uri
            .baseUri("http://localhost:8088/")
            .pathParam("employee_id", requestEmployeeId)
            .when() //actual action is to perform the get request
            .get("employees/{employee_id}")
            .then() // will return the ValidatadleResponse from the Response object
            .statusCode(200)
            .extract()
            .as(Employee.class);

    Assert.assertEquals(actualResponse, expectedResponse);
}

3. Validating the response with Json String in Rest Assured

We can compare the 2 json Strings with JSONAssert.assertEquals method.

Here we are converting the response into String by calling the asString() method. We got the response in json from rest assured get call and stored into the actualResponse and now we can compare the actualResponse and expectedResponse with JSONAssert.assertEquals method.

@Test
public void validateWithJsonString() throws JSONException {
    String requestEmployeeId = "2";
    String expectedJson = "{"id":2,"firstName":"only","lastName":"fullstack","salary":2000,"email":"onlyfullstack@abc.com"}";
    String actualResponse = RestAssured.given() //precondition is to give the base uri
            .baseUri("http://localhost:8088/")
            .pathParam("employee_id", requestEmployeeId)
            .when() //actual action is to perform the get request
            .get("employees/{employee_id}")
            .asString();

    System.out.println(response);
    JSONAssert.assertEquals(expectedJson, actualResponse, true);
}

4. Validating response from file in Rest Assured

We can get the expectedResponse as String in Json format from file and then we can compare the 2 json Strings with JSONAssert.assertEquals method.

Here we are converting the response into String by calling the asString() method. We got the response in json from rest assured get call and stored into the actualResponse and now we can compare the actualResponse and expectedResponse with JSONAssert.assertEquals method.

@Test
public void validateWithJsonFromFile() throws IOException, JSONException {
    String requestEmployeeId = "2";
    String expectedJsonResponse = new String(Files.readAllBytes(Paths.get("src/test/resources/single-employee.json")));
    String actualJsonResponse = RestAssured.given() //precondition is to give the base uri
            .baseUri("http://localhost:8088/")
            .pathParam("employee_id", requestEmployeeId)
            .when() //actual action is to perform the get request
            .get("employees/{employee_id}")
            .asString();

    System.out.println(actualJsonResponse);
    JSONAssert.assertEquals(expectedJsonResponse, actualJsonResponse, true);
}

5. Validating the response with Json Schema in Rest Assured

We can also compare the Json with the Json schema by validating the structure of JSON data.


What is Json Schema?
JSON Schema is a specification for JSON based format for defining the structure of JSON data. Json Schema will tell us the datatype of each property or attribute of the json can hold. you can find the Json Schema for our employee get api on below link –
https://github.com/onlyfullstack/rest-assured-tutorial/blob/master/src/test/resources/get-all-employee-json-schema.json

How to generate the Json Schema?
Usually you will get the Json schema from the requiremnt or user story and if you haven’t got then you can generate them based on the sample Json. I have used below website to generate the Json Schema.
https://www.liquid-technologies.com/online-json-to-schema-converter

We can use JsonSchemaValidator.matchesJsonSchemaInClasspath() method and provide the employee schema which needs to be validated against the Json response.

@Test
public void validateJsonSchema() {
    RestAssured.given()
            .baseUri("http://localhost:8088")
            .get("/employees")
            .then()
            .statusCode(200)
            .body(JsonSchemaValidator.matchesJsonSchemaInClasspath("get-all-employee-json-schema.json"));
}

Lets go to our next tutorial where we will discuss below points :

Part 9 – Different ways to provide body in Rest Assured

– Different ways to provide body in HTTP Post with Rest Assured
– 1. Input Body as simple Json String in Rest Assured
– 2. Input Body as Map in Rest Assured
– 3. Input Body as Object in Rest Assured
– 4. Input Body from file in Rest Assured
https://www.onlyfullstack.com/ways-to-pass-request-body-in-rest-assured/

Source Code
You can find the complete source code on below GitHub repository – 
https://github.com/onlyfullstack/rest-assured-tutorial

Rest Assured Tutorial
https://www.onlyfullstack.com/rest-assured-tutorial-for-beginners/