Data Driven Testing With TestNG and Excel
Last Updated :
01 Aug, 2025
Data-Driven Testing with TestNG is a powerful approach that allows you to run the same test case with multiple sets of data. By using external data sources like Excel or CSV files, you can easily manage and maintain your test data, making your testing process more efficient and reliable.
Here are the steps of data-driven Testing using TestNG’s DataProvider in combination with Excel files for providing login details to a Selenium test case.
Step 1: Prepare Your Excel File
Create an Excel file
that contains multiple sets of login credentials. Each row will represent a new dataset.
loginData.xlsx
Username | Password |
---|
standard_user | secret_sauce |
locked_out_user | secret_sauce |
problem_user | secret_sauce |
loginData excel Step 2: Add Required Dependencies
Ensure you have the necessary dependencies in your pom.xml if you are using Maven:
XML
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0</version>
</dependency>
</dependencies>
Step 3: Create a Utility to Read Excel Data.
To read data from the Excel file, we will create a utility method using Apache POI. This method will read the Excel file and return the data in a 2D Object[][]
array, which is required by TestNG's DataProvider.
ExcelUtils.java
Java
package io.learn.datadriven;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelUtils {
public static Object[][] getExcelData(String filePath, String sheetName) throws IOException, InvalidFormatException {
FileInputStream file = new FileInputStream(new File(filePath));
Workbook workbook = WorkbookFactory.create(file);
Sheet sheet = workbook.getSheet(sheetName);
int rowCount = sheet.getPhysicalNumberOfRows();
int colCount = sheet.getRow(0).getPhysicalNumberOfCells();
Object[][] data = new Object[rowCount - 1][colCount]; // To ignore the header row
for (int i = 1; i < rowCount; i++) { // Start from 1 to skip the header row
for (int j = 0; j < colCount; j++) {
data[i - 1][j] = sheet.getRow(i).getCell(j).toString();
}
}
workbook.close();
return data;
}
}
Make sure:
- getExcelData(): This method reads data from the Excel file and stores it in a 2D array (
Object[][]
). - File Path: You must provide the file path of the Excel file you want to read from.
- Sheet Name: Specify the name of the sheet from which you want to extract data.
Step 4: Create the DataProvider Method
We have a utility to read data from Excel, we can use this method in our DataProvider. Update our DataProviderExample
class to read data from the Excel file and supply it to the test.
DataProviderExample.java
Java
package io.learn.datadriven;
import org.testng.annotations.DataProvider;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.IOException;
public class DataProviderExample {
@DataProvider(name = "loginData")
public Object[][] provideLoginData() throws IOException, InvalidFormatException {
// Provide the path to the Excel file and the sheet name
return ExcelUtils.getExcelData("change the path of excelfile in your local storage\\loginData.xlsx", "Sheet_Name which we give at the bottom in Excel File");
}
}
loginData DataProvider method is updated to call the ExcelUtils.getExcelData()
method to get the login data from the loginData.xlsx
file.
Step 5: Create the Selenium Test Class
In the next step, create the Selenium test class that uses the loginData
DataProvider for the login test. We will perform the login with each set of username and password provided by the Excel file.
LoginTest.java
Java
package io.learn.datadriven;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class LoginTest {
WebDriver driver;
@BeforeMethod
public void setUp() {
// Initialize the WebDriver (ensure chromedriver path is correct)
System.setProperty("webdriver.chrome.driver", "C:\\Users\\change the path of chromedriver path\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.saucedemo.com/"); // URL of the login page
}
@Test(dataProvider = "loginData", dataProviderClass = DataProviderExample.class)
public void testLogin(String username, String password) {
// Find elements for username, password, and login button
WebElement usernameField = driver.findElement(By.id("user-name"));
WebElement passwordField = driver.findElement(By.id("password"));
WebElement loginButton = driver.findElement(By.id("login-button"));
// Clear any existing text from fields
usernameField.clear();
passwordField.clear();
// Input login credentials from DataProvider
usernameField.sendKeys(username);
passwordField.sendKeys(password);
loginButton.click();
System.out.println("The DataDriven test executed successfully");
// Validate the login behavior by checking the title of the page
Assert.assertTrue(driver.getTitle().contains("Swag Labs"));
}
@AfterMethod
public void tearDown() {
driver.quit(); // Close the browser after each test
}
}
Step 5: Running the Tests
To run the tests, execute the following command in the terminal or use your IDE's test runner:
mvn test
If you are using your IDE, you can run the test directly.
Output:
DataProvider in TestNG with data from an Excel file outputBy using DataProvider in TestNG with data from an Excel file, you can efficiently run tests with multiple data sets without hardcoding the test data.
Similar Reads
Software Testing Tutorial Software testing is an important part of the software development lifecycle that involves verifying and validating whether a software application works as expected. It ensures reliable, correct, secure, and high-performing software across web, mobile applications, cloud, and CI/CD pipelines in DevOp
10 min read
What is Software Testing? Software testing is an important process in the Software Development Lifecycle(SDLC). It involves verifying and validating that a Software Application is free of bugs, meets the technical requirements set by its Design and Development, and satisfies user requirements efficiently and effectively.Here
11 min read
Principles of Software testing - Software Testing Software testing is an important aspect of software development, ensuring that applications function correctly and meet user expectations. From test planning to execution, analysis and understanding these principles help testers in creating a more structured and focused approach to software testing,
3 min read
Software Development Life Cycle (SDLC) Software Development Life Cycle (SDLC) is a structured process that is used to design, develop, and test high-quality software. SDLC, or software development life cycle, is a methodology that defines the entire procedure of software development step-by-step. The goal of the SDLC life cycle model is
8 min read
Software Testing Life Cycle (STLC) The Software Testing Life Cycle (STLC) is a process that verifies whether the Software Quality meets the expectations or not. STLC is an important process that provides a simple approach to testing through the step-by-step process, which we are discussing here. Software Testing Life Cycle (STLC) is
7 min read
Types of Software Testing Software testing is a important aspect of software development life-cycle that ensures a product works correctly, meets user expectations, and is free of bugs. There are different types of software testing, each designed to validate specific aspects of an application, such as functionality, performa
15+ min read
Levels of Software Testing Software Testing is an important part of the Software Development Life Cycle which is help to verify the product is working as expected or not. In SDLC, we used different levels of testing to find bugs and errors. Here we are learning those Levels of Testing in detail.Table of ContentWhat Are the Le
4 min read
Test Maturity Model - Software Testing The Test Maturity Model (TMM) in software testing is a framework for assessing the software testing process to improve it. It is based on the Capability Maturity Model(CMM). It was first produced by the Illinois Institute of Technology to assess the maturity of the test processes and to provide targ
8 min read
SDLC MODELS
TYPES OF TESTING