Monday, 1 May 2017

Data-Driven Testing Using Selenium and Excel: Complete Java Tutorial

 


Introduction

In software testing, the same functionality often needs to be tested with multiple sets of input data. For example, a login page may need validation using valid credentials, incorrect passwords, blank fields and invalid usernames.

Writing a separate Selenium test script for every input combination can make an automation project repetitive and difficult to maintain.

Data-driven testing solves this problem by separating test data from test logic. Instead of hardcoding input values into test scripts, testers maintain data in external sources such as Excel spreadsheets, CSV files, databases or JSON files.

In Selenium automation using Java, Excel is a popular option for managing test data. The Apache POI library helps Java programs read and process Excel workbooks.

This tutorial explains how to integrate Selenium, Java, Excel and TestNG to create a basic data-driven automation test.

1. What Is Data-Driven Testing?

Data-driven testing is an automation approach in which a single test script executes multiple times using different input data.

For example, consider a login application.

Test CaseUsernamePasswordExpected Result
TC01validuservalid123Login successful
TC02validuserwrong123Login unsuccessful
TC03invaliduservalid123Login unsuccessful
TC04blankblankValidation message

Instead of writing four separate scripts, one Selenium test method can execute all four scenarios using data supplied from an external file.

2. Advantages of Data-Driven Testing

  • Reuses the same automation script with multiple inputs.

  • Reduces duplicate test code.

  • Makes test data easier to maintain.

  • Helps validate positive and negative scenarios.

  • Supports larger regression test suites.

  • Allows testers and business teams to review test data separately from automation code.

3. Tools Required

To implement data-driven testing using Selenium and Excel, you will need:

  1. Java Development Kit (JDK).

  2. Eclipse or IntelliJ IDEA.

  3. Selenium WebDriver.

  4. Apache Maven.

  5. TestNG.

  6. Apache POI.

  7. Microsoft Excel or a compatible spreadsheet application.

4. Create a Maven Project and Add Dependencies

Create a Maven project in Eclipse or IntelliJ IDEA.

Add the following dependencies to your pom.xml file:

<dependencies>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.38.0</version>
    </dependency>

    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.11.0</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.4.1</version>
        <scope>test</scope>
    </dependency>

</dependencies>

These are example dependency versions. Check compatibility and use suitable current releases when creating a new project.

Apache POI provides Java APIs for working with Excel files, including .xlsx workbooks.

5. Create an Excel Test Data File

Create an Excel file named TestData.xlsx.

Add a worksheet called LoginData and enter the following information:

UsernamePasswordExpected Result
validuservalid123Success
validuserwrong123Failure
invaliduservalid123Failure
blankblankFailure

Save the file in the project's test resources folder, for example:

src/test/resources/TestData.xlsx

The test application must contain corresponding test accounts and predictable responses for these scenarios. The sample values above are illustrative.

6. Read Excel Data Using Apache POI

Apache POI provides classes such as:

  • FileInputStream – opens the Excel file.

  • Workbook – represents the workbook.

  • Sheet – represents a worksheet.

  • Row – represents a row.

  • Cell – represents a cell.

Create a utility class named ExcelUtils.java.

package utilities;

import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtils {

    public static Object[][] getExcelData(String filePath)
            throws Exception {

        try (FileInputStream fis =
                 new FileInputStream(filePath);
             Workbook workbook = new XSSFWorkbook(fis)) {

            Sheet sheet = workbook.getSheet("LoginData");

            int rowCount = sheet.getLastRowNum();

            int columnCount =
                sheet.getRow(0).getLastCellNum();

            Object[][] data =
                new Object[rowCount][columnCount];

            DataFormatter formatter = new DataFormatter();

            for (int i = 1; i <= rowCount; i++) {

                Row row = sheet.getRow(i);

                for (int j = 0; j < columnCount; j++) {

                    Cell cell = row.getCell(
                        j,
                        Row.MissingCellPolicy.CREATE_NULL_AS_BLANK
                    );

                    data[i - 1][j] =
                        formatter.formatCellValue(cell);
                }
            }

            return data;
        }
    }
}

This utility reads the worksheet and returns its contents as a two-dimensional Java array.

The first row is treated as the header and excluded from the test data.

For production frameworks, additional checks should be added for missing worksheets, empty files and inconsistent column structures.

7. Connect Excel Data with TestNG DataProvider

TestNG provides the @DataProvider annotation to supply multiple sets of data to a test method.

Create a test class named LoginDataTest.java.

package tests;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import utilities.ExcelUtils;

public class LoginDataTest {

    @DataProvider(name = "loginData")
    public Object[][] getLoginData() throws Exception {

        String filePath =
            "src/test/resources/TestData.xlsx";

        return ExcelUtils.getExcelData(filePath);
    }

    @Test(dataProvider = "loginData")
    public void loginTest(
            String username,
            String password,
            String expectedResult) {

        System.out.println("Username: " + username);
        System.out.println("Password: " + password);
        System.out.println("Expected: " + expectedResult);
    }
}

When TestNG executes this test, it invokes the same test method once for each row returned by the DataProvider.

This example demonstrates data delivery. The next step is to connect the supplied data to actual Selenium browser interactions.

8. Execute Selenium Login Tests Using Excel Data

The following example shows how Excel data can be used to execute a Selenium login test.

package tests;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;
import org.testng.annotations.*;

public class SeleniumExcelTest {

    WebDriver driver;

    @BeforeMethod
    public void setUp() {

        driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://example.com/login");
    }

    @Test(dataProvider = "loginData",
          dataProviderClass = LoginDataTest.class)
    public void verifyLogin(
            String username,
            String password,
            String expectedResult) {

        driver.findElement(By.id("username"))
              .sendKeys(username);

        driver.findElement(By.id("password"))
              .sendKeys(password);

        driver.findElement(By.id("login"))
              .click();

        boolean loginSuccessful =
            driver.getCurrentUrl().contains("dashboard");

        if (expectedResult.equalsIgnoreCase("Success")) {
            Assert.assertTrue(
                loginSuccessful,
                "Expected successful login"
            );
        } else {
            Assert.assertFalse(
                loginSuccessful,
                "Expected login failure"
            );
        }
    }

    @AfterMethod(alwaysRun = true)
    public void tearDown() {

        if (driver != null) {
            driver.quit();
        }
    }
}

Important: This is an illustrative example. Replace the URL, element locators and success-condition logic with those of the actual application. In a production test, use an application-specific result message or other reliable validation instead of relying only on URL changes.

9. Excel vs CSV vs Database for Test Data

Data sourceAdvantagesTypical use
ExcelEasy to review and maintainSmall and medium test data sets
CSVLightweight and simpleStructured tabular data
DatabaseSupports large and structured datasetsEnterprise applications
JSONSupports nested data structuresAPI and complex test scenarios

The choice depends on project size, data complexity, team preferences and maintenance requirements.

10. Best Practices for Data-Driven Automation

  1. Keep test data separate from automation logic.

  2. Use meaningful Excel worksheet and column names.

  3. Avoid hardcoding file paths throughout the framework.

  4. Validate missing or blank cells.

  5. Use DataFormatter when reading mixed Excel cell types.

  6. Do not store real passwords or sensitive credentials in plain Excel files.

  7. Use a separate test-data management approach for large projects.

  8. Maintain reusable Excel-reading utilities.

  9. Capture test results and execution logs.

  10. Use TestNG reports to track passed and failed scenarios.

Frequently Asked Questions

1. What is data-driven testing in Selenium?

It is an approach where the same Selenium test script executes with multiple input data sets.

2. Which library is used to read Excel files in Selenium Java?

Apache POI is a widely used Java library for reading and writing Excel workbooks.

3. What is TestNG DataProvider?

@DataProvider supplies multiple sets of input data to a TestNG test method.

4. Can Selenium read Excel files directly?

Selenium does not provide native Excel-reading functionality. Java libraries such as Apache POI are commonly used for this purpose.

5. Can data-driven testing be implemented without Excel?

Yes. CSV, JSON, databases and other data sources can also be used.

6. Why is data-driven testing important?

It reduces duplicated scripts, improves test coverage and makes it easier to maintain multiple test scenarios.

Learn Selenium Automation Testing with Palium Skills

Palium Skills offers practical Selenium and Playwright automation testing training for freshers, manual testers and working professionals.

The training curriculum can include:

  • Selenium WebDriver with Java and Python.

  • Data-driven testing using Excel and Apache POI.

  • TestNG and PyTest frameworks.

  • XPath and CSS Selector techniques.

  • Page Object Model and framework development.

  • API testing and automation.

  • Maven, Git and Jenkins integration.

  • Real-time automation projects.

  • Interview preparation and career guidance.

Training modes: Classroom training at South Kolkata and Salt Lake centres, along with instructor-led live online sessions for learners across India.

Contact Palium Skills

South Kolkata Centre: 1st Floor, Sheeba Bhavan, 1/22 Poddar Nagar (Near South City Mall), Kolkata – 700068.

Salt Lake Centre: 5th Floor, RDB Boulevard, Block GP, Salt Lake Electronic Complex, Kolkata – 700091.

Build practical Selenium automation skills with Palium Skills through classroom and live online training.

No comments:

Post a Comment

TDS on Salary: A Practical Guide for HR and Payroll Professionals

  TDS on Salary: A Complete Guide for HR and Payroll Professionals Learn how TDS on salary works in India , the role of employers, employee...