Answer
Data-Driven Testing in Cucumber BDD
Approach 1: Scenario Outline + Examples (Built-in — Most Common)
Gherkin
Feature: Login Validation
Scenario Outline: Login with multiple users
Given the user is on the login page
When the user enters "<username>" and "<password>"
Then the result should be "<expected>"
Examples:
| username | password | expected |
| admin@test.com | Admin@123 | Dashboard |
| user@test.com | User@456 | Home Page |
| wrong@test.com | badpass | Invalid Credentials |
| locked@test.com | Locked@123 | Account Locked |
Step Definition:
Java
@When("the user enters {string} and {string}")
public void enterCredentials(String username, String password) {
driver.findElement(By.id("email")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
}
@Then("the result should be {string}")
public void verifyResult(String expected) {
assertTrue(driver.getPageSource().contains(expected));
}
Approach 2: DataTable (Inline Table in Step)
Gherkin
Scenario: Register with full form data
Given the user fills in the registration form:
| Field | Value |
| FirstName | John |
| LastName | Doe |
| Email | john@example.com |
| Mobile | 9876543210 |
| Password | Test@123 |
Then the user should be registered successfully
Step Definition with DataTable:
Java
@Given("the user fills in the registration form:")
public void fillRegistrationForm(DataTable dataTable) {
Map<String, String> formData = dataTable.asMap(String.class, String.class);
driver.findElement(By.id("firstName")).sendKeys(formData.get("FirstName"));
driver.findElement(By.id("lastName")).sendKeys(formData.get("LastName"));
driver.findElement(By.id("email")).sendKeys(formData.get("Email"));
driver.findElement(By.id("mobile")).sendKeys(formData.get("Mobile"));
driver.findElement(By.id("password")).sendKeys(formData.get("Password"));
}
Approach 3: External Data (Excel/JSON)
Java
// Read from Excel using Apache POI
@When("the user tests login with external data")
public void loginWithExternalData() throws Exception {
FileInputStream fis = new FileInputStream("testdata/login.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
String username = row.getCell(0).getStringCellValue();
String password = row.getCell(1).getStringCellValue();
// perform login with each row
}
workbook.close();
}
Comparison
| Approach | Best For | Visibility |
|---|---|---|
| Scenario Outline | Simple tabular data | Feature file (BA visible) |
| DataTable | Complex form data | Feature file (BA visible) |
| External Excel/JSON | Large data sets | Java only (not in feature file) |
