Answer
Data Tables in Cucumber
Definition
A Data Table is a table of values passed directly within a Gherkin step using the pipe | character as column separator. Unlike Scenario Outline (which drives multiple scenario runs), a Data Table passes all data to a single step execution.
Syntax
Gherkin
When the user submits the following form data:
| Field | Value |
| FirstName | John |
| Email | john@example.com |
| Phone | 9876543210 |
Use Cases
1. Form Submission
Gherkin
Scenario: Submit contact form
When the user fills in the contact form with:
| Name | Alice Smith |
| Email | alice@example.com |
| Message | Hello, I need help |
Then the form should be submitted successfully
2. Verifying a List
Gherkin
Scenario: Verify product list
Then the homepage should display these products:
| Laptop |
| Phone |
| Tablet |
| Watch |
3. API Request Body
Gherkin
Scenario: Create new user via API
When I send a POST request to "/api/users" with:
| Field | Value |
| name | John Doe |
| email | john@test.com |
| role | ADMIN |
Then the response status should be 201
Accessing DataTable in Step Definition
Java
import io.cucumber.datatable.DataTable;
import java.util.*;
// As Map<String,String> (key-value pairs)
@When("the user fills in the contact form with:")
public void fillForm(DataTable dataTable) {
Map<String, String> data = dataTable.asMap(String.class, String.class);
driver.findElement(By.id("name")).sendKeys(data.get("Name"));
driver.findElement(By.id("email")).sendKeys(data.get("Email"));
}
// As List<String> (single column)
@Then("the homepage should display these products:")
public void verifyProducts(DataTable dataTable) {
List<String> expectedProducts = dataTable.asList(String.class);
for (String product : expectedProducts) {
assertTrue(driver.getPageSource().contains(product),
"Product not found: " + product);
}
}
// As List<Map<String,String>> (multiple rows with headers)
@When("the admin creates these users:")
public void createUsers(DataTable dataTable) {
List<Map<String, String>> users = dataTable.asMaps(String.class, String.class);
for (Map<String, String> user : users) {
createUser(user.get("name"), user.get("email"), user.get("role"));
}
}
DataTable vs Scenario Outline
| DataTable | Scenario Outline | |
|---|---|---|
| Runs scenario | Once | Multiple times (one per row) |
| Data access | Via DataTable object | Via method parameters |
| Header row | Optional | Required (= placeholder names) |
| Use case | Structured data for one action | Multiple test iterations |
