Three Essential Approaches for Passing Test Data in Automation Frameworks: JSON, Static DataProvider, and Excel

 

Three Essential Approaches for Passing Test Data in Automation Frameworks: JSON, Static DataProvider, and Excel

In modern test automation frameworks, passing test data efficiently is crucial for making tests reusable, maintainable, and scalable. In this blog, we’ll cover three powerful ways to pass data in an automation framework using TestNG’s DataProvider feature. These methods offer flexibility to manage test data from various sources like JSON, Excel, or hardcoded data within the test suite.


1. Using DataProvider with JSON (External File)

One of the most efficient ways to manage test data is by using JSON files. JSON files can store structured data in key-value pairs, which is easy to parse and pass into test cases. Here’s how to achieve this using TestNG’s DataProvider in combination with a JSON file.

Steps:

  • Read JSON file
  • Convert JSON into a POJO
  • Pass the POJO data using DataProvider

1.1 Sample JSON File (testData.json)

{
"users": [
{
"username": "testUser1",
"password": "password123"
},
{
"username": "testUser2",
"password": "password456"
}
]
}

1.2 Create a ReadFile Class to Read the JSON

This class will help read the JSON file from the resources folder as a string:

package com.opensourceFramework.utils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;
public class ReadFile {
public String readFileAsString(String fileName) {
BufferedReader br = null;
String jsonString = "";
try {
String sCurrentLine;
String path = Paths.get(".").toAbsolutePath().normalize().toString();
br = new BufferedReader(new FileReader(path + "/src/main/resources/" + fileName));
while ((sCurrentLine = br.readLine()) != null) {
jsonString += sCurrentLine;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonString;
}
}

1.3 POJO Class for JSON Data

We will create a POJO (Plain Old Java Object) to map the JSON structure.

package com.opensourceFramework.pojo;
public class User {
private String username;
private String password;
// Getters and Setters
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

1.4 DataProvider Method to Pass Data to Test

Next, let’s implement the DataProvider to read JSON, convert it to a POJO, and pass the data to the test.

package com.opensourceFramework.tests;
import com.google.gson.Gson;
import com.opensourceFramework.pojo.User;
import com.opensourceFramework.utils.ReadFile;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class LoginTest {

@DataProvider(name = "userData")
public Object[][] getUserData() {
String json = new ReadFile().readFileAsString("testData.json");
Gson gson = new Gson();
User[] users = gson.fromJson(json, User[].class); // Convert JSON to User array
Object[][] data = new Object[users.length][1];
for (int i = 0; i < users.length; i++) {
data[i][0] = users[i];
}
return data;
}
@Test(dataProvider = "userData")
public void loginTest(User user) {
System.out.println("Username: " + user.getUsername());
System.out.println("Password: " + user.getPassword());
// Add your login test logic here
}
}

2. Using a Static DataProvider

Sometimes, you may prefer using static data directly within your test class. This is the simplest way to manage test data, where you hard-code the values inside the test itself.

2.1 DataProvider with Static Data Example

package com.opensourceFramework.tests;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class StaticDataProviderTest {
@DataProvider(name = "staticData")
public Object[][] provideStaticData() {
return new Object[][] {
{"testUser1", "password123"},
{"testUser2", "password456"}
};
}
@Test(dataProvider = "staticData")
public void loginTest(String username, String password) {
System.out.println("Username: " + username);
System.out.println("Password: " + password);
// Add your login test logic here
}
}

This method is ideal for simple tests with minimal or hardcoded test data. It’s straightforward, though not suitable for larger datasets or dynamic test data.

3. Using DataProvider with Excel or CSV File

Handling large test data or configuration values often requires the use of Excel or CSV files. You can use libraries like Apache POI to read Excel files and pass the data into your test cases.

Steps:

  • Read Excel file using Apache POI
  • Convert data into a format consumable by DataProvider

3.1 Maven Dependency for Apache POI

Add this dependency to your pom.xml:

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>

3.2 Utility Class to Read Excel File

package com.opensourceFramework.utils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
public class ExcelReader {
public Object[][] readExcelData(String fileName, String sheetName) {
Object[][] data = null;
try {
String path = Paths.get(".").toAbsolutePath().normalize().toString();
FileInputStream fis = new FileInputStream(path + "/src/main/resources/" + fileName);
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheet(sheetName);
int rowCount = sheet.getPhysicalNumberOfRows();
int colCount = sheet.getRow(0).getLastCellNum();
data = new Object[rowCount - 1][colCount];
for (int i = 1; i < rowCount; i++) {
Row row = sheet.getRow(i);
for (int j = 0; j < colCount; j++) {
data[i - 1][j] = row.getCell(j).toString();
}
}
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}

3.3 DataProvider Using Excel Data

package com.opensourceFramework.tests;
import com.opensourceFramework.utils.ExcelReader;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ExcelDataProviderTest {
@DataProvider(name = "excelData")
public Object[][] getExcelData() {
return new ExcelReader().readExcelData("testData.xlsx", "LoginData");
}
@Test(dataProvider = "excelData")
public void loginTest(String username, String password) {
System.out.println("Username: " + username);
System.out.println("Password: " + password);
// Add your login test logic here
}
}

Conclusion

Passing data in test automation frameworks can be efficiently done using TestNG’s DataProvider feature. Whether you prefer storing data in JSON files, using static data, or working with Excel files, the right approach depends on your project needs. The techniques explained in this blog allow you to handle a variety of test data sources with ease, ensuring flexibility and scalability in your automation suite.

Comments

Popular posts from this blog

Building a Mock API Framework in Java Using Spring Boot

Mastering Selenium Automation with Docker and the Page Object Model Framework

Maven: Solving Build and Dependency Management Challenges