In this blog, we’ll look at how to validate status code using a JSON file in Rest-assured to conduct data-driven testing. This method is useful when testing a dynamic data and validating dynamic status code.
Prerequisites:
Basic Knowledge of Java.
a JSON data file that you can use as the test's source.
Data Driven Testing in Rest-assured:
Data-driven testing is a software testing methodology where test scripts are executed using a set of data. This technique is particularly useful in API testing, where various input parameters can lead to numerous test scenarios. Rest-assured, a Java-based library used for testing RESTful web services, supports data-driven testing, making it an ideal tool for comprehensive API testing. This report delves into the steps and benefits of implementing DDT in Rest-assured, demonstrating how it enhances test coverage and efficiency.
JSON File:
A JSON file is a file that stores simple data structures and objects in JavaScript Object Notation(JSON) format,
which is a standard data interchange format. It is primarily used for transmitting data between a web application and a server. JSON files are lightweight, text-based, human-readable, and can be edited using a text editor.
Methods
To implement data-driven testing in Rest-assured, the following steps are essential:
Create a Maven project in eclipse
Click finish to create a project.
Setup Rest-assured and TestNG: Ensure that Rest-assured and TestNG libraries are included in your maven project dependencies(Pom.xml). Add the below two dependencies in the pom.xml. Go to https://mvnrepository.com/ maven repository website to get the latest version of the dependencies, use search textbox to get the respective dependency.
Add three package(API_Pojo,Utilities and API_Test)
Create three class files for the respective packages as shown below:
Create a JSON file(creatpost.json) in the resources folder as below:
Create Test Data: Store test data in external sources such as Excel files, CSV files, JSON or databases. I choose to save it in JSON file(createpost.json)
Open filename.java from Utilities package and give the filename and path of JSON file.
package Utilities;
public class Filenames {
//Set up a base path URL
public static final String Base_Path="./src/test/resources/";
//Set up a json file path
public static final String JsonData= Base_Path + "createpost.json";
}
Then in the Createuser.java pojo file create a getter and setter for all the data variable. Here we create name, job and statuscode as string variable and added two constructor with different parameter. One constructor has name and job as parameter and other constructor has statuscode as parameter. In the next step will see how we are fetch data using this constructor and object mapper.
package API_Pojo;
public class CreateUser {
//Declare the variable for the test data and source code validation
private String name;
private String job;
private String statuscode;
public CreateUser()
{
}
//Constructor for name and job
public CreateUser(String fname,String job1)
{
setName(fname);
setJob(job1);
}
//constructor for status code
public CreateUser(String status)
{
setStatuscode(status);
}
//Getter and setter for all the variables that is declared.
public String getStatuscode() {
return statuscode;
}
public void setStatuscode(String statuscode) {
this.statuscode = statuscode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
Parameterize Tests: Use TestNG’s @DataProvider annotation to pass different sets of data to the test methods using JSON file.
In the Datadrivencreate.java file that is in the API_test package include the Dataprovider. Data from the json file are treated as object and its assigned to the object as shown below. using for loop we are iterating to get the data.
@DataProvider(name="getdata")
public Object[] gettestdatajson() {
Object[] obj=null;
try {
String Jsontestdata= FileUtils.readFileToString(new File(Filenames.JsonData),"UTF-8");
JSONArray jsonarray=JsonPath.read(Jsontestdata,"$");
obj= new Object[jsonarray.size()];
for(int i=0; i<jsonarray.size();i++)
{
obj[i]=jsonarray.get(i);
}
} catch (IOException e) {
e.printStackTrace();
}
return obj;
}
Write testcase in the Datadrivecreate.java file and provide the data provider name.
package API_test;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import org.apache.commons.io.FileUtils;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import Utilities.Filenames;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import net.minidev.json.JSONArray;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.JsonPath;
import API_Pojo.CreateUser;
import static org.hamcrest.Matchers.equalTo;
public class Datadrivencreate {
@Test (dataProvider="getdata")
public void DDusingJson(LinkedHashMap<String,String> testdata) throws Exception
{
//Calling the pojo call with the respecting parameters
CreateUser newuser= new CreateUser(testdata.get("name"),testdata.get("job"));
ObjectMapper objectmapper=new ObjectMapper();
String requestBody=objectmapper.writerWithDefaultPrettyPrinter().writeValueAsString(newuser);
//getting status code from json file and assigning to int variable.
int Statuscode= Integer.parseInt( testdata.get("Statuscode"));
Response response=
RestAssured
.given()
.contentType(ContentType.JSON)
.body(requestBody)
.baseUri("https://reqres.in/api/users")
.when()
.post()
.then()
.assertThat()
//Validating the status code.
.statusCode(equalTo(Statuscode))
.extract()
.response();
}
@DataProvider(name="getdata")
public Object[] gettestdatajson() {
Object[] obj=null;
try {
String Jsontestdata= FileUtils.readFileToString(new File(Filenames.JsonData),"UTF-8");
JSONArray jsonarray=JsonPath.read(Jsontestdata,"$");
obj= new Object[jsonarray.size()];
for(int i=0; i<jsonarray.size();i++)
{
obj[i]=jsonarray.get(i);
}
} catch (IOException e) {
e.printStackTrace();
}
return obj;
}
}
Execute Tests: Run the tests with varying data sets and validate the API responses using textng.xml file.
Run the testng.xml file to validate the status code for POST request.
Conclusion - We now have a Data driven testing framework for Rest-assured, which reads a single JSON file for the input data along with status code to validate. We can have multiple test data for multiple end points along with status code to test and validate a different endpoint.