How to pass the request body from an external file in a separate package in Rest Assured?

Rest AssuredDynamic ProgrammingProgramming

We can pass the request body from an external file in a separate package in Rest Assured and pass that file directly to a request as a payload. This technique can be used for static payloads or payloads having slight changes.

The RequestSpecification interface has a method called the body. It is an overloaded method that can send payloads in various formats.

Let us create a JAVA file, say PayLoad.java, and add a request body in the below format. This is created within the project in a separate package.

Code Implementation in PayLoad.java

package files;
public class PayLoad {
   public static String pay_load() {
      return "{\n" + " \"Place\": \"Michigan\",\n" + " \"Transport\": \"Car\"\n" + "}";
   }
}

Code Implementation in NewTest.java

import org.testng.annotations.Test;
import files.PayLoad;
import static io.restassured.RestAssured.given;
import io.restassured.RestAssured;
public class NewTest {
   @Test
   public void externalPayLoad() {

      //base URL
      RestAssured.baseURI = "https://run.mocky.io/v3";

      //POST operation
      given().header("Content-type", "application/json")

      //adding post method with payload from external file
      .body(PayLoad.pay_load()).when()
      .post("/9fbf4a2b-00fa-41bb-a0a8-658ada897509")
      .then().log().all()

      //verify status code as 201
     .assertThat().statusCode(201);
   }
}

Output

raja
Published on 17-Nov-2021 11:43:32
Advertisements