How to use Assertion in response in Rest Assured?

Rest AssuredDynamic ProgrammingProgramming

We can use Assertion in response in Rest Assured. To obtain the Response we need to use the methods - Response.body or Response.getBody. Both these methods are a part of the Response interface.

Once a Response is obtained it is converted to string with the help of the asString method. This method is a part of the ResponseBody interface. We can then obtain the JSON representation of the Response body with the help of the jsonPath method. Finally, we shall verify the JSON content to explore a particular JSON key with its value.

We shall first send a GET request via Postman on a mock API URL and go through the Response body.

Using Rest Assured, we shall check if the value of the key - Location is Michigan.

Example

Code Implementation

import org.testng.Assert;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.response.ResponseBody;
import io.restassured.specification.RequestSpecification;
public class NewTest {
   @Test
   void respAssertion() {

      //base URI with Rest Assured class
      RestAssured.baseURI = "https://run.mocky.io/v3";

      //input details
      RequestSpecification h = RestAssured.given();

      //get response
      Response r = h.get("/0cb0e329-3dc8-4976-a14b-5e5e80e3db92");

      //Response body
      ResponseBody bdy = r.getBody();

      //convert response body to string
      String b = bdy.asString();

      //JSON Representation from Response Body
      JsonPath j = r.jsonPath();

      //Get value of Location Key
      String l = j.get("Location");
      System.out.println(l);

      // verify the value of key
      Assert.assertTrue(l.equalsIgnoreCase("Michigan"));
   }
}

Output

raja
Published on 22-Nov-2021 10:25:51
Advertisements