Practical 21: Behavior-Driven Development with Cucumber
Aim
Write Cucumber feature files that describe how the website should behave. Use Gherkin steps and connect them to Java methods. Use Selenium to perform the browser actions and check the results.
Theory
Behaviour-Driven Development (BDD) helps users, developers and testers agree on what software should do. They write examples of expected behaviour before building or changing it.
Gherkin writes these examples with words such as Given, When and Then. Cucumber matches the steps to code and runs them as tests.
The feature file is a written recipe: "Given the oven is hot, When I bake for 20 minutes, Then the cake is golden". The owner, the chef and the food tester all understand it. The step definitions are the actual cooking actions behind each line, and Cucumber is the kitchen assistant who reads the recipe line by line and does each action.
flowchart LR
BA[Business / BA<br/>writes scenarios in Gherkin] --> F[.feature files]
F --> C[Cucumber runner]
C --> SD[Step definitions<br/>Java + Selenium]
SD --> APP[Web application]
C --> R[Reports<br/>HTML / JSON]
Gherkin keywords
| Keyword | Meaning |
|---|---|
Feature |
The capability being described (one per file) |
Background |
Steps run before every scenario in the feature |
Scenario |
One concrete example of behaviour |
Given |
Pre-condition / initial context |
When |
The action / event |
Then |
The expected outcome (assertions) |
And, But |
Continue the previous Given/When/Then |
Scenario Outline + Examples |
Same scenario run with several data rows (<placeholders>) |
@tag |
Tags such as @smoke to select scenarios |
""" / ` |
` tables |
Cucumber expressions in step definitions
| Gherkin text | Step definition |
|---|---|
Given the user is on the login page |
@Given("the user is on the login page") |
When the user logs in as "student" with password "Pass@123" |
@When("the user logs in as {string} with password {string}") |
Then the cart should contain 2 items |
@Then("the cart should contain {int} items") |
Parameter types: {string}, {int}, {float}, {word}.
Hooks
@Before and @After (from io.cucumber.java) run before/after each scenario – for example start and quit the browser, take a screenshot when a scenario fails.
Requirements
The .test addresses refer to the simulated practice app. Outside the simulator, use a running test app and its actual addresses and page elements.
- Eclipse with the Cucumber Eclipse plugin (syntax colouring for
.featurefiles), JDK (Java Development Kit) 17. - Maven dependencies:
cucumber-java,cucumber-junit(orcucumber-junit-platform-engine),selenium-java,junit.
<dependencies>
<dependency><groupId>io.cucumber</groupId><artifactId>cucumber-java</artifactId><version>7.18.0</version></dependency>
<dependency><groupId>io.cucumber</groupId><artifactId>cucumber-junit</artifactId><version>7.18.0</version><scope>test</scope></dependency>
<dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-java</artifactId><version>4.21.0</version></dependency>
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency>
</dependencies>
Project structure:
CucumberBDD
├── pom.xml
└── src/test
├── java/vlp/bdd
│ ├── runner/TestRunner.java
│ └── steps/LoginSteps.java, CartSteps.java, Hooks.java
└── resources/features
├── login.feature
└── cart.feature
Procedure
- Create a Maven project
CucumberBDDand add the dependencies. - Write the feature files under
src/test/resources/features. - Run once – Cucumber prints snippets for undefined steps; copy them into step-definition classes.
- Implement the steps with Selenium WebDriver.
- Create the runner and run it as a JUnit Test; open the HTML (Hypertext Markup Language) report.
login.feature
@login
Feature: User login
As a registered customer
I want to log in to the VLP Demo Store
So that I can view my orders and check out
Background:
Given the user is on the login page
@smoke
Scenario: Successful login with valid credentials
When the user logs in as "student" with password "Pass@123"
Then the dashboard should be displayed
And the welcome message should be "Welcome, student"
Scenario Outline: Login fails with invalid credentials
When the user logs in as "<username>" with password "<password>"
Then an error message "<message>" should be shown
Examples:
| username | password | message |
| student | wrong | Invalid username or password |
| nobody | Pass@123 | Invalid username or password |
| | | Username and password are required |
cart.feature
@cart
Feature: Shopping cart
Scenario: Add two products to the cart
Given the user is logged in as "student"
When the user adds "Wireless Mouse" to the cart
And the user adds "USB-C Charger" to the cart
Then the cart should contain 2 items
And the cart total should be "₹ 1,598"
Hooks.java and a shared driver
package vlp.bdd.steps;
import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.Scenario;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class Hooks {
public static WebDriver driver;
@Before
public void startBrowser() {
driver = new ChromeDriver();
driver.manage().window().maximize();
}
@After
public void closeBrowser(Scenario scenario) {
if (scenario.isFailed()) {
byte[] png = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
scenario.attach(png, "image/png", scenario.getName());
}
driver.quit();
}
}
LoginSteps.java
package vlp.bdd.steps;
import static org.junit.Assert.*;
import java.time.Duration;
import io.cucumber.java.en.*;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.*;
public class LoginSteps {
private final String BASE = "https://demo.virtuallp.test/";
private WebDriverWait waitFor() { return new WebDriverWait(Hooks.driver, Duration.ofSeconds(10)); }
@Given("the user is on the login page")
public void the_user_is_on_the_login_page() {
Hooks.driver.get(BASE + "login");
assertEquals("Login – VLP Demo Store", Hooks.driver.getTitle());
}
@Given("the user is logged in as {string}")
public void the_user_is_logged_in_as(String user) {
the_user_is_on_the_login_page();
the_user_logs_in_as_with_password(user, "Pass@123");
waitFor().until(ExpectedConditions.urlContains("/dashboard"));
}
@When("the user logs in as {string} with password {string}")
public void the_user_logs_in_as_with_password(String user, String pass) {
Hooks.driver.findElement(By.id("username")).sendKeys(user);
Hooks.driver.findElement(By.id("password")).sendKeys(pass);
Hooks.driver.findElement(By.cssSelector("button[type=submit]")).click();
}
@Then("the dashboard should be displayed")
public void the_dashboard_should_be_displayed() {
waitFor().until(ExpectedConditions.urlContains("/dashboard"));
}
@Then("the welcome message should be {string}")
public void the_welcome_message_should_be(String expected) {
assertEquals(expected, Hooks.driver.findElement(By.cssSelector(".welcome")).getText());
}
@Then("an error message {string} should be shown")
public void an_error_message_should_be_shown(String expected) {
String actual = waitFor().until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".alert-error"))).getText();
assertEquals(expected, actual);
}
}
CartSteps.java
package vlp.bdd.steps;
import static org.junit.Assert.*;
import java.time.Duration;
import io.cucumber.java.en.*;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.*;
public class CartSteps {
private int expectedCount = 0;
@When("the user adds {string} to the cart")
public void the_user_adds_to_the_cart(String product) {
WebDriver d = Hooks.driver;
WebDriverWait wait = new WebDriverWait(d, Duration.ofSeconds(10));
WebElement search = d.findElement(By.id("search"));
search.clear();
search.sendKeys(product + Keys.ENTER);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".product-card .add"))).click();
expectedCount++;
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id("cart-count"), String.valueOf(expectedCount)));
}
@Then("the cart should contain {int} items")
public void the_cart_should_contain_items(int count) {
assertEquals(String.valueOf(count), Hooks.driver.findElement(By.id("cart-count")).getText());
}
@Then("the cart total should be {string}")
public void the_cart_total_should_be(String total) {
Hooks.driver.findElement(By.id("cart-link")).click();
assertEquals(total, Hooks.driver.findElement(By.id("cart-total")).getText());
}
}
TestRunner.java
package vlp.bdd.runner;
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 = "vlp.bdd.steps",
plugin = { "pretty", "html:target/cucumber-report.html", "json:target/cucumber.json" },
tags = "not @wip",
monochrome = true
)
public class TestRunner { }
Run: right-click TestRunner → Run As → JUnit Test, or mvn test. Run only smoke tests with -Dcucumber.filter.tags="@smoke".
Virtual lab · Testing Tools · 40 min
Behaviour-driven development with Cucumber
Run Gherkin feature files against the VLP Demo Store, turn undefined steps into Java step definitions from Cucumber’s snippets, get all scenarios green and filter runs with tags.
Output (pretty plugin)
Example output for the settings in this lesson:
@login
Feature: User login
Background:
Given the user is on the login page # LoginSteps.the_user_is_on_the_login_page()
@smoke
Scenario: Successful login with valid credentials # login.feature:11
When the user logs in as "student" with password "Pass@123"
Then the dashboard should be displayed
And the welcome message should be "Welcome, student"
...
5 Scenarios (5 passed)
18 Steps (18 passed)
0m15.170s
The HTML report (target/cucumber-report.html) lists each feature, scenario and step with pass/fail status and attached screenshots for failures.
Observations
- The Scenario Outline run three times, once per Examples row.
- The Background step ran before every login scenario.
- An unimplemented step is reported as Undefined with a ready-to-paste snippet; a failing assertion marks the step Failed and subsequent steps Skipped.
Conclusion
Run the feature files and check that each Gherkin step matches a Java step definition. Read the passed and failed scenarios in the report. Check that the browser actions match the behaviour written in the feature file.
Viva questions
- What is BDD? How does it differ from TDD (Test-Driven Development)? BDD describes behaviour in business-readable scenarios agreed by everyone; TDD starts from developer-level unit tests.
- Explain the Gherkin keywords with an example. Feature, Background, Scenario, Given (context), When (action), Then (result), And/But, Scenario Outline + Examples, tags – for example the login feature above.
- What is the role of step definitions? How does Cucumber match steps to them? They are the Java code behind each step; Cucumber matches the step text to the annotation's Cucumber expression or regex.
- Differentiate Scenario and Scenario Outline. A Scenario runs once with fixed values; a Scenario Outline runs once per row of its Examples table.
- What is a Background? Steps that run before every scenario in the feature file.
- What are Cucumber hooks?
@Before/@Aftermethods that run around each scenario – for example start and quit the browser, take a screenshot on failure. - Explain the
@CucumberOptionsattributesfeatures,glue,pluginandtags. features = where the .feature files are; glue = package of step definitions and hooks; plugin = report formats; tags = which scenarios to run. - What does Cucumber report for a step with no matching definition? The step is undefined, and Cucumber prints a code snippet to implement it.
Practise this topic
Hands-on virtual lab
Apply what you just read in a realistic, guided simulation. Free with a verified account.
Create a free account to track your progress and unlock virtual labs.