Validate Response Body using Rest Assured

When a request is made to the server for the particular details, the server responds by sending the details as a Response body. The response interface contains two methods to get the Response Body.

Method 1:

Response.body(): returns ResponseBody

Response.getBody(): returns ResponseBody               


These are available under io.restassured.response.ResponseBody. This class represents the Body of a received Response. It helps to validate complete or parts of the Response Body. ResponseBody interface also has a method called .asString(), using which ResponseBody can be converted into its String representation.


// Retrieve the body of the Response

ResponseBody responsebody = response.getBody()

Note: Response.body() method does exactly the same thing, thus the code can also be executed as below:

ResponseBody responsebody = response.body()


//Convert it into String

String responseString= responsebody.asString();

The response body which is in JSON format is converted into String format using the method asString().


//Validate Response Body contains some String

Assert.assertEquals(responseString.contains("placed"), true, "Response body contains Hyderabad");

Note: The method String.contains() is used to verify if the Response contain that particular string.


Complete Example Code
@Test 
public void GetDetail() {

RestAssured.baseURI = "https://petstore.swagger.io/v2/store/order";
RequestSpecification httpRequest = RestAssured.given();
Response response = httpRequest.get("/1");

// Retrive the body of Response
ResponseBody responsebody = response.getBoody();

// Convert the Response to String type
String responseString= responsebody.asString();

// Assert that result contains the expected string
Assert.assertEquals(responseString.toLowerCase().contains("placed"), true, "Expected string");

}
}

 

Method2:

It can also be verified through a shorter version of code to validate the response body with REST Assured. In the BDD framework, this method is usually followed. 

// Validate the body contains expected string

.then().assertThat().body(status, equalTo("placed") );

In the then statement the assert statement is used to verify the variable value (in our case it is status) is equal to the expected result (our case it is placed). If the expected is matched with the result the assert return true or else False. 



Complete
Example Code
@Test 
public void GetDetail() {

RestAssured.baseURI = "https://petstore.swagger.io/v2/store/order";

RestAssured.given()

.when()

.get("/1")

.then().statusCode(200).assertThat().
body("status", equalTo("placed") );));


}