Selenium Data Driven Testing
Data driven testing runs the same test script multiple times using different input values pulled from an external source, like an Excel file or a CSV file. One login test can check ten different username and password combinations without writing ten separate test methods.
Diagram: One Script, Many Data Sets
[Data Source: Excel File]
Row 1: user1, pass1
Row 2: user2, pass2
Row 3: user3, pass3
|
v
[Single Login Test Method]
|
v
Runs 3 times, once per row
TestNG DataProvider
TestNG includes a built-in feature called DataProvider that feeds different data sets into the same test method automatically.
@DataProvider(name = "loginData")
public Object[][] getLoginData() {
return new Object[][] {
{"student1@estudy247.com", "pass123"},
{"student2@estudy247.com", "pass456"},
{"student3@estudy247.com", "pass789"}
};
}
@Test(dataProvider = "loginData")
public void testLogin(String email, String password) {
driver.findElement(By.id("email")).sendKeys(email);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.id("login-btn")).click();
}
TestNG runs testLogin() three separate times, once for each row inside the array, passing the correct email and password pair each time.
Reading Data From Excel
Apache POI is the standard library for reading and writing Excel files in Java. A helper method opens the file, loops through rows, and returns the values as an array.
FileInputStream fis = new FileInputStream("testdata.xlsx");
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
String email = row.getCell(0).getStringCellValue();
String password = row.getCell(1).getStringCellValue();
System.out.println(email + " - " + password);
}
This loop reads every row from the first sheet, printing each email and password pair stored in the spreadsheet.
Reading Data From CSV
BufferedReader reader = new BufferedReader(new FileReader("testdata.csv"));
String line;
while ((line = reader.readLine()) != null) {
String[] values = line.split(",");
System.out.println(values[0] + " - " + values[1]);
}
CSV files split each line by a comma character, giving the same two values without needing an external library like Apache POI.
Benefits Of Data Driven Testing
- Adding a new test case means adding a new row in the data file, not writing new code.
- Non-technical team members can update test data without touching Java code.
- The same script covers valid data, invalid data, and edge cases through different rows.
Practical Example
A course discount coupon feature needs testing with five different coupon codes, some valid and some expired. A single test method reads all five codes from an Excel sheet, applies each one during checkout, and confirms the correct discount or error message appears for every row.
