What is Data-Driven Testing in Cucumber Using Examples Keyword?
Data-Driven Testing in Cucumber is a method that allows you to run the same scenario multiple times with different sets of data. This is done using the Scenario Outline and Examples keywords in the Gherkin language.
Why Use Data-Driven Testing?
Eliminates code duplication
Increases test coverage
Allows testing edge cases easily
Makes test scenarios readable and maintainable
Gherkin Keywords Used
| Keyword | Description |
|---|---|
| Scenario Outline | Used when you want to run the same scenario with multiple data sets |
| Examples | Contains the table of input values that will be injected into the scenario |
Syntax Example
Feature File: login.feature
Feature: Login Feature Scenario Outline: Valid login with multiple credentials Given User is on the login page When User enters username "<username>" and password "<password>" Then User should see the dashboard Examples: | username | password | | user1 | pass123 | | user2 | password1 | | admin | admin123 |
Step Definition in Java
File: LoginSteps.java
package stepDefinitions; import io.cucumber.java.en.*; public class LoginSteps { @Given("User is on the login page") public void user_is_on_the_login_page() { System.out.println("User navigates to login page"); } @When("User enters username {string} and password {string}") public void user_enters_username_and_password(String username, String password) { System.out.println("Entered Username: " + username); System.out.println("Entered Password: " + password); } @Then("User should see the dashboard") public void user_should_see_the_dashboard() { System.out.println("User lands on the dashboard"); } }
Test Runner Class
package testRunner; import org.junit.runner.RunWith; import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; @RunWith(Cucumber.class) @CucumberOptions( features = "src/test/resources/features", glue = {"stepDefinitions"}, plugin = {"pretty", "html:target/cucumber-reports.html"}, monochrome = true ) public class TestRunner { }
Project Structure
src/
└── test/
└── java/
└── stepDefinitions/
└── LoginSteps.java
└── testRunner/
└── TestRunner.java
└── resources/
└── features/
└── login.feature
Output
User navigates to login page Entered Username: user1 Entered Password: pass123 User lands on the dashboard User navigates to login page Entered Username: user2 Entered Password: password1 User lands on the dashboard User navigates to login page Entered Username: admin Entered Password: admin123 User lands on the dashboard
Important Points:
| Feature | Description |
|---|---|
| Data-Driven Testing | Run one scenario with multiple data sets |
| Scenario Outline | Defines a scenario template |
| Examples | Data table used for substitution in the scenario |
| Benefit | Avoids duplication, increases maintainability and test coverage |