Open In App

Data Driven Testing With TestNG and Excel

Last Updated : 01 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

UsernamePassword
standard_usersecret_sauce
locked_out_usersecret_sauce
problem_usersecret_sauce
Excel-File-for-Data-driven-testing
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-output
DataProvider in TestNG with data from an Excel file output

By 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