KEMBAR78
Data Seeding via Parameterized API Requests | PDF
Data Seeding via Parameterized API Requests
Data Seeding via Parameterized API Requests
Steps for Configuring RestAssured
1. Create a maven project in Eclipse.
Please find the sample project structure below:
2. Add the following dependencies in pom.xml and update the project.
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.11</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.13</version>
© RapidValue Solutions 2
Data Seeding via Parameterized API Requests
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.13</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.13</version>
</dependency>
3. Create a new package and a new class.
In src/test/java, create a package ‘com.rvs.httpmethods’ and a java file
‘RequestParameterization.java’
4. Add TestNG library to the project.
Right click on Project -> Build Path -> Add Libraries -> TestNG
5. Start coding.
Data-driven Testing
For data-driven testing, the test values are read directly from the data files rather than using hard
coded values. The data files can be csv files, excel files, text files, etc. A test containing several
sets of hard coded values can be difficult to modify and maintain. It’s alway easier and a best
practice to extend values in the data file than to modify the actual test scripts. Various inputs or
data modifications can be handled easily without even touching the actual test script.
© RapidValue Solutions 3
Data Seeding via Parameterized API Requests
Data-driven test performs following operation in a loop:
- Retrieving input data from storage.
- Parameterizing the required data in the Api request body.
- Sending the request and verifying the response received.
In the example of parameterizing the request body, you have to create an excel sheet with the test
details. This data set basically contains the number and the employee name, which you have to
parameterize in the request.
Test data example is given below, which should be created at
"/src/test/resources/Employees.xlsx”: Sheet name should be “Employees”.
The following is the method that uses Apache POI library functions to fetch test data from the
excel sheet and it will return the data as object.
© RapidValue Solutions 4
Data Seeding via Parameterized API Requests
TestNG Data Providers
REST Assured can be combined with TestNG, and it provides an easy mechanism to create data-
driven tests through the DataProvider.
public Object[][] getDataFromSheet(String TESTDATA_SHEET_PATH, String sheetName) {
FileInputStream file = null;
try {
file = new FileInputStream(TESTDATA_SHEET_PATH);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
book = WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sheet = book.getSheet(sheetName);
Object[][] data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()];
for (int i = 0; i < sheet.getLastRowNum(); i++) {
for (int k = 0; k < sheet.getRow(0).getLastCellNum(); k++) {
data[i][k] = sheet.getRow(i + 1).getCell(k).toString();
}
}
return data;
}
© RapidValue Solutions 5
Data Seeding via Parameterized API Requests
A Data Provider is a method annotated with @DataProvider. A Data Provider returns an
array of objects. It helps you to write data-driven tests which essentially means that same test
method can be run multiple times with different data-sets.
Parameterization allows you to pick different values at run time. It reduces time and effort.
Here, the TestData() method is annotated with @DataProvider annotation and the same is used in
@Test configuration. DataProvider method will return an object array and its dimension must
match the test method. Since your test method has two arguments, the DataProvider method must
return object[][] so that it can be mapped to the arguments in the method.
Here, you need to make sure that the array returned by the DataProvider should match the test
method parameters.
JSON File Creation
A JSON file is a file that stores simple data structures and objects in JavaScript Object Notation
(JSON) format.
In order to create a JSON file in the project, right click on “src/test/resources” and click on
New> Other. On selecting Other option, you will get several options. From these options,
select General > File option, and then click Next. You can create a JSON file by giving the
name “AddEmployee” and ".json" extension and click on finish button. You need to add the
request body in the created JSON file.
@DataProvider
public Object[][] TestData() throws Exception {
String dir = System.getProperty("user.dir");
Object[][] testObjArray = DataProviderUtils.getDataFromSheet(dir +
"//src//test//resources//Employees.xlsx", "Employees");
return (testObjArray);
}
© RapidValue Solutions 6
Data Seeding via Parameterized API Requests
Here, the name inside the curly braces {} will be replaced with the values fetched from the excel
sheet.
Create Multiple Employees
The below method will send the post request with the parameters provided and it will return the
response.
{
"name": "${name}",
"salary": "100100",
"age": "25"
}
public Response postRequest(String URI, String resource, String payloadFolderPath, String
EmpName) throws IOException {
String payloadPath = payloadFolderPath;
String payload = new String(Files.readAllBytes(Paths.get(payloadPath)));
System.out.println(EmpName);
payload = payload.replace("${name}", EmpName);
System.out.println("Payload is" + "n" + payload);
Response resp = RestAssured.given().baseUri(URI)
.body(payload)
.contentType("application/json")
.log().all()
.when()
.post(resource).andReturn();
return resp;
}
AddEmployee.json
© RapidValue Solutions 7
Data Seeding via Parameterized API Requests
The following method will create multiple employees.
@Test(dataProvider="TestData")
public void createMultipleEmployees(String EmpID, String EmpName) throws IOException {
String baseURI = “http: //dummy.restapiexample.com”;
String resource = “/api/v1/ create”;
String dir = System.getProperty("user.dir");
String payloadPath = dir + "//src//test//resources//AddEmployee.json”;
resp = postRequest(baseURI, resource, payloadPath, EmpName);
JSONObject jObj = new JSONObject(resp.getBody().asString());
String emp_id = jObj.getString("id");
String emp_name = jObj.getString("name");
empName.add(emp_name);
empID.add(emp_id);
System.out.println("Created Employee Datails");
empData = new String[empID.size()][2];
}
for (int i = 0; i < empID.size(); i++) {
empData[i][0] = empID.get(i);
empData[i][1] = empName.get(i);
System.out.println(empData[i][0] + " - " + empData[i][1]);
}
© RapidValue Solutions 8
Data Seeding via Parameterized API Requests
Test Execution Output
Conclusion
Parameterization is very important for automation testing. It helps you to iterate on input data
with multiple data sets that make your scripts reusable and maintainable. In few scenarios, you
can still manage with hard coded request but the same approach will not work out where sheer
count of combinations is to be validated. By implementing the right solution, you can keep your
code base and test data size at ideal range and still savor the benefits of optimal coverage.
Hope this blog helped you to understand the concept of parameterization and the actual
implementation in a better way.
Happy Learning!
By,
Mary Geethu, C. A.
Senior Software Engineer
© RapidValue Solutions 9
Data Seeding via Parameterized API Requests
About RapidValue
RapidValue is a global leader in digital product engineering solutions including mobility, omni-channel,
IoT, AI, RPA and cloud to enterprises worldwide. RapidValue offers its digital services to the world’s top
brands, Fortune 1000 companies and innovative emerging start-ups. With offices in the United States, the
United Kingdom, Germany and India and operations spread across the Middle-East, Europe and Canada,
RapidValue delivers enterprise services and solutions across various industry verticals.
Disclaimer:
This document contains information that is confidential and proprietary to RapidValue Solutions Inc. No part of it may be used,
circulated, quoted, or reproduced for distribution outside RapidValue. If you are not the intended recipient of this report, you are
hereby notified that the use, circulation, quoting, or reproducing of this report is strictly prohibited and may be unlawful.
© RapidValue Solutions
www.rapidvaluesolutions.com/blogwww.rapidvaluesolutions.com
+1 877.643.1850 contactus@rapidvaluesolutions.com
© RapidValue Solutions 10

Data Seeding via Parameterized API Requests

  • 1.
    Data Seeding viaParameterized API Requests
  • 2.
    Data Seeding viaParameterized API Requests Steps for Configuring RestAssured 1. Create a maven project in Eclipse. Please find the sample project structure below: 2. Add the following dependencies in pom.xml and update the project. <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.11</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.13</version> © RapidValue Solutions 2
  • 3.
    Data Seeding viaParameterized API Requests </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.13</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.13</version> </dependency> 3. Create a new package and a new class. In src/test/java, create a package ‘com.rvs.httpmethods’ and a java file ‘RequestParameterization.java’ 4. Add TestNG library to the project. Right click on Project -> Build Path -> Add Libraries -> TestNG 5. Start coding. Data-driven Testing For data-driven testing, the test values are read directly from the data files rather than using hard coded values. The data files can be csv files, excel files, text files, etc. A test containing several sets of hard coded values can be difficult to modify and maintain. It’s alway easier and a best practice to extend values in the data file than to modify the actual test scripts. Various inputs or data modifications can be handled easily without even touching the actual test script. © RapidValue Solutions 3
  • 4.
    Data Seeding viaParameterized API Requests Data-driven test performs following operation in a loop: - Retrieving input data from storage. - Parameterizing the required data in the Api request body. - Sending the request and verifying the response received. In the example of parameterizing the request body, you have to create an excel sheet with the test details. This data set basically contains the number and the employee name, which you have to parameterize in the request. Test data example is given below, which should be created at "/src/test/resources/Employees.xlsx”: Sheet name should be “Employees”. The following is the method that uses Apache POI library functions to fetch test data from the excel sheet and it will return the data as object. © RapidValue Solutions 4
  • 5.
    Data Seeding viaParameterized API Requests TestNG Data Providers REST Assured can be combined with TestNG, and it provides an easy mechanism to create data- driven tests through the DataProvider. public Object[][] getDataFromSheet(String TESTDATA_SHEET_PATH, String sheetName) { FileInputStream file = null; try { file = new FileInputStream(TESTDATA_SHEET_PATH); } catch (FileNotFoundException e) { e.printStackTrace(); } try { book = WorkbookFactory.create(file); } catch (InvalidFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } sheet = book.getSheet(sheetName); Object[][] data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()]; for (int i = 0; i < sheet.getLastRowNum(); i++) { for (int k = 0; k < sheet.getRow(0).getLastCellNum(); k++) { data[i][k] = sheet.getRow(i + 1).getCell(k).toString(); } } return data; } © RapidValue Solutions 5
  • 6.
    Data Seeding viaParameterized API Requests A Data Provider is a method annotated with @DataProvider. A Data Provider returns an array of objects. It helps you to write data-driven tests which essentially means that same test method can be run multiple times with different data-sets. Parameterization allows you to pick different values at run time. It reduces time and effort. Here, the TestData() method is annotated with @DataProvider annotation and the same is used in @Test configuration. DataProvider method will return an object array and its dimension must match the test method. Since your test method has two arguments, the DataProvider method must return object[][] so that it can be mapped to the arguments in the method. Here, you need to make sure that the array returned by the DataProvider should match the test method parameters. JSON File Creation A JSON file is a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format. In order to create a JSON file in the project, right click on “src/test/resources” and click on New> Other. On selecting Other option, you will get several options. From these options, select General > File option, and then click Next. You can create a JSON file by giving the name “AddEmployee” and ".json" extension and click on finish button. You need to add the request body in the created JSON file. @DataProvider public Object[][] TestData() throws Exception { String dir = System.getProperty("user.dir"); Object[][] testObjArray = DataProviderUtils.getDataFromSheet(dir + "//src//test//resources//Employees.xlsx", "Employees"); return (testObjArray); } © RapidValue Solutions 6
  • 7.
    Data Seeding viaParameterized API Requests Here, the name inside the curly braces {} will be replaced with the values fetched from the excel sheet. Create Multiple Employees The below method will send the post request with the parameters provided and it will return the response. { "name": "${name}", "salary": "100100", "age": "25" } public Response postRequest(String URI, String resource, String payloadFolderPath, String EmpName) throws IOException { String payloadPath = payloadFolderPath; String payload = new String(Files.readAllBytes(Paths.get(payloadPath))); System.out.println(EmpName); payload = payload.replace("${name}", EmpName); System.out.println("Payload is" + "n" + payload); Response resp = RestAssured.given().baseUri(URI) .body(payload) .contentType("application/json") .log().all() .when() .post(resource).andReturn(); return resp; } AddEmployee.json © RapidValue Solutions 7
  • 8.
    Data Seeding viaParameterized API Requests The following method will create multiple employees. @Test(dataProvider="TestData") public void createMultipleEmployees(String EmpID, String EmpName) throws IOException { String baseURI = “http: //dummy.restapiexample.com”; String resource = “/api/v1/ create”; String dir = System.getProperty("user.dir"); String payloadPath = dir + "//src//test//resources//AddEmployee.json”; resp = postRequest(baseURI, resource, payloadPath, EmpName); JSONObject jObj = new JSONObject(resp.getBody().asString()); String emp_id = jObj.getString("id"); String emp_name = jObj.getString("name"); empName.add(emp_name); empID.add(emp_id); System.out.println("Created Employee Datails"); empData = new String[empID.size()][2]; } for (int i = 0; i < empID.size(); i++) { empData[i][0] = empID.get(i); empData[i][1] = empName.get(i); System.out.println(empData[i][0] + " - " + empData[i][1]); } © RapidValue Solutions 8
  • 9.
    Data Seeding viaParameterized API Requests Test Execution Output Conclusion Parameterization is very important for automation testing. It helps you to iterate on input data with multiple data sets that make your scripts reusable and maintainable. In few scenarios, you can still manage with hard coded request but the same approach will not work out where sheer count of combinations is to be validated. By implementing the right solution, you can keep your code base and test data size at ideal range and still savor the benefits of optimal coverage. Hope this blog helped you to understand the concept of parameterization and the actual implementation in a better way. Happy Learning! By, Mary Geethu, C. A. Senior Software Engineer © RapidValue Solutions 9
  • 10.
    Data Seeding viaParameterized API Requests About RapidValue RapidValue is a global leader in digital product engineering solutions including mobility, omni-channel, IoT, AI, RPA and cloud to enterprises worldwide. RapidValue offers its digital services to the world’s top brands, Fortune 1000 companies and innovative emerging start-ups. With offices in the United States, the United Kingdom, Germany and India and operations spread across the Middle-East, Europe and Canada, RapidValue delivers enterprise services and solutions across various industry verticals. Disclaimer: This document contains information that is confidential and proprietary to RapidValue Solutions Inc. No part of it may be used, circulated, quoted, or reproduced for distribution outside RapidValue. If you are not the intended recipient of this report, you are hereby notified that the use, circulation, quoting, or reproducing of this report is strictly prohibited and may be unlawful. © RapidValue Solutions www.rapidvaluesolutions.com/blogwww.rapidvaluesolutions.com +1 877.643.1850 contactus@rapidvaluesolutions.com © RapidValue Solutions 10