How to use TestNG data providers for parameterization in Rest Assured?

Rest AssuredDynamic ProgrammingProgramming

We can use TestNG data providers for parameterization in Rest Assured. Using data providers we can execute a single test case in multiple runs. To know more about TestNG data providers visit the below link −

https://www.tutorialspoint.com/testng/testng_parameterized_test.htm

This technique can be used for dynamic payloads. For this, we shall create a Java class containing the payload.

Then in the second Java class (having the implementation of the POST request), we shall pass the dynamic fields of the payload as parameters to the request body.

Please find the project structure for the implementation below.

Example

Code Implementation in NewTest.java

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import io.restassured.RestAssured;
public class NewTest {

   //data provider annotation
   @Test(dataProvider="Title")
   void dataProvPayLoad(String title, String body) {

      //base URL
      RestAssured.baseURI = "https://jsonplaceholder.typicode.com";

      //input details
      given().header("Content-type", "application/json")

      //adding post method with parameterization from data provider
      .body(PayLoad.postBody(title, body)).
      when().post("/posts").then()

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

   //data provider method
   @DataProvider(name="Title")
   public Object[][] getData() {
      //multi-dimension element collection with two data sets
      return new Object[][]
      {{"Cypress","JavaScript"},{"Selenium","Python"}};
   }
}

Code Implementation in PayLoad.java

public class PayLoad {
   public static String postBody(String title, String body) {
      //request payload
      String b = "{\n" +
      //Parameterizing title and body fields
      "\"title\": \"" +title+ " \",\n" + "\"body\": \"" +body+ " \",\n" + " \"userId\": \"34\" \n}";
      return b;
   }
}

Output

raja
Updated on 17-Nov-2021 13:00:26

Advertisements