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


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 = "{
" +       //Parameterizing title and body fields       "\"title\": \"" +title+ " \",
" + "\"body\": \"" +body+ " \",
" + " \"userId\": \"34\"
}"; return b; } }

Output

Updated on: 17-Nov-2021

846 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements