Answer
Examples Keyword in Cucumber
Purpose
Examples keyword is used to supply test data to a Scenario Outline. Every row in the Examples table results in one execution of the scenario with that row's values substituted into the <placeholder> tokens.
Rules
- ✓
Examplesmust followScenario Outline— it cannot be used with regularScenario - ✓First row is the header (column names = placeholder names)
- ✓Each subsequent row is one test execution
- ✓Column names must exactly match the
<placeholders>in the scenario
Syntax
Gherkin
Scenario Outline: Verify product prices
Given the user is on the product catalog page
When the user searches for "<product>"
Then the price displayed should be "<price>"
And the availability should be "<availability>"
Examples:
| product | price | availability |
| Laptop | $999 | In Stock |
| Phone | $599 | In Stock |
| Tablet | $399 | Out of Stock |
| Watch | $199 | In Stock |
This runs 4 tests — one for each data row.
Multiple Examples Blocks
You can have multiple Examples sections with tags:
Gherkin
Scenario Outline: Login test
When the user logs in as "<username>"
Then the result should be "<outcome>"
@smoke
Examples: Valid Users
| username | outcome |
| admin | Dashboard |
| user | Home |
@negative
Examples: Invalid Users
| username | outcome |
| hacker | Access Denied |
| unknown | User not found |
In Step Definitions
Parameters from Examples are passed as method arguments in the same order they appear in the step:
Java
@When("the user searches for {string}")
public void searchProduct(String product) {
// Called once per Examples row with that row's value
searchBox.sendKeys(product);
}
@Then("the price displayed should be {string}")
public void verifyPrice(String expectedPrice) {
assertEquals(expectedPrice, priceElement.getText());
}
