Cucumber BDD Tutorial with Selenium and Java
Build a working Cucumber 7 project with Selenium 4 and Java: feature files, step definitions, hooks, shared state, tags and reports, explained step by step.
Many teams adopt Cucumber because a manager wants “tests the business can read”, and six months later they have hundreds of feature files nobody outside QA opens, plus step definitions that are harder to maintain than plain Selenium code. Cucumber works well when it is used for what it is good at: describing behaviour in shared language, backed by clean automation code, and that is the approach this Cucumber BDD tutorial follows.
We will build a small working project with Cucumber 7, Selenium 4, Java 17 and the JUnit Platform. You will write a feature file, step definitions, hooks for browser setup, share state between steps the recommended way, run tests by tag and generate a report. Along the way, we will cover the practices that keep a Cucumber suite readable as it grows.
Key takeaways
- BDD is a collaboration practice first; Cucumber is the tool that turns agreed examples into automated checks.
- Write Gherkin in business language: what the user does and sees, not which button ID is clicked.
- Keep step definitions thin. Put page interaction in page objects and share state through dependency injection.
- Use hooks for setup and teardown, and attach screenshots on failure.
- Tags let you run smoke, regression or feature-specific subsets without separate projects.
What BDD and Cucumber actually are
Behaviour-Driven Development (BDD) is a way for product owners, developers and testers to agree on how a feature should behave using concrete examples, before the code is written. Those examples are written in Gherkin, a structured plain-English format using Given, When and Then.
Cucumber reads Gherkin feature files and matches each step to a Java method, called a step definition. Selenium then drives the browser inside those methods. So the layers are:
| Layer | What it contains | Who reads it |
|---|---|---|
| Feature file | Scenarios in Gherkin | Whole team, including business |
| Step definitions | Java glue code for each step | QA and developers |
| Page objects | Locators and page actions | QA and developers |
| Selenium WebDriver | Browser automation | Code only |
If your team never discusses scenarios before development, you are using Cucumber as a test runner with extra overhead. That can still work, but be honest about it in interviews. BDD fits naturally into agile ceremonies; our Agile interview questions for testers cover how “three amigos” sessions work.
Cucumber BDD tutorial setup with Maven
Add these dependencies to pom.xml. Cucumber’s JUnit Platform engine is the currently recommended runner, and PicoContainer handles sharing state between step classes.
<properties>
<cucumber.version>7.20.1</cucumber.version>
</properties>
<dependencies>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit-platform-engine</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-picocontainer</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-suite</artifactId>
<version>1.11.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.11.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.25.0</version>
</dependency>
</dependencies>Use Maven Surefire 3.x so JUnit Platform tests are discovered. The project layout:
src/test/java
pages/LoginPage.java
runner/RunCucumberTest.java
steps/Hooks.java
steps/LoginSteps.java
steps/TestContext.java
src/test/resources
features/login.featureStep 1: Write the feature file
Create src/test/resources/features/login.feature. This uses a public practice login page.
Feature: Login
As a registered user
I want to log in
So that I can reach my secure area
Background:
Given I am on the login page
@smoke
Scenario: Successful login
When I log in with username "tomsmith" and password "SuperSecretPassword!"
Then I should see the message "You logged into a secure area!"
Scenario Outline: Login fails with wrong credentials
When I log in with username "<username>" and password "<password>"
Then I should see the message "<message>"
Examples:
| username | password | message |
| wronguser | SuperSecretPassword! | Your username is invalid! |
| tomsmith | wrongpass | Your password is invalid! |Key Gherkin elements here:
- Feature describes the capability, with an optional user story.
- Background runs before every scenario in the file.
- Scenario is one concrete example.
- Scenario Outline with Examples runs the same steps for each data row.
- Tags like
@smokelabel scenarios for selective runs.
Step 2: Create a page object
Step definitions should not contain locators. Put them in a page class, as you would in any framework built on the Page Object Model.
package pages;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LoginPage {
private final WebDriver driver;
private final WebDriverWait wait;
private final By username = By.id("username");
private final By password = By.id("password");
private final By loginButton = By.cssSelector("button[type='submit']");
private final By flash = By.id("flash");
public LoginPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
public LoginPage open() {
driver.get("https://the-internet.herokuapp.com/login");
return this;
}
public void submit(String user, String pass) {
wait.until(ExpectedConditions.visibilityOfElementLocated(username)).sendKeys(user);
driver.findElement(password).sendKeys(pass);
driver.findElement(loginButton).click();
}
public String flashMessage() {
return wait.until(ExpectedConditions.visibilityOfElementLocated(flash)).getText();
}
}Step 3: Share state and manage the browser with hooks
Cucumber creates new step definition objects for every scenario. To share the driver between Hooks and LoginSteps, use a context class that PicoContainer injects into both constructors.
package steps;
import org.openqa.selenium.WebDriver;
public class TestContext {
private WebDriver driver;
public WebDriver getDriver() {
return driver;
}
public void setDriver(WebDriver driver) {
this.driver = driver;
}
}package steps;
import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.Scenario;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Hooks {
private final TestContext context;
public Hooks(TestContext context) {
this.context = context;
}
@Before
public void startBrowser() {
context.setDriver(new ChromeDriver());
}
@After
public void closeBrowser(Scenario scenario) {
WebDriver driver = context.getDriver();
if (driver == null) {
return;
}
if (scenario.isFailed()) {
byte[] png = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
scenario.attach(png, "image/png", scenario.getName());
}
driver.quit();
}
}Note that io.cucumber.java.Before is a Cucumber hook, not the JUnit annotation with the same name. Importing the wrong one is a classic beginner mistake.
Step 4: Write step definitions
package steps;
import static org.junit.jupiter.api.Assertions.assertTrue;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import pages.LoginPage;
public class LoginSteps {
private final TestContext context;
private LoginPage loginPage;
public LoginSteps(TestContext context) {
this.context = context;
}
@Given("I am on the login page")
public void iAmOnTheLoginPage() {
loginPage = new LoginPage(context.getDriver()).open();
}
@When("I log in with username {string} and password {string}")
public void iLogIn(String username, String password) {
loginPage.submit(username, password);
}
@Then("I should see the message {string}")
public void iShouldSeeTheMessage(String expected) {
String actual = loginPage.flashMessage();
assertTrue(actual.contains(expected), "Actual message: " + actual);
}
}{string} is a Cucumber Expression parameter that captures quoted text. Other built-in types include {int}, {float} and {word}. Cucumber Expressions are easier to read than regular expressions, which older tutorials use.
Step 5: Add a runner and execute
package runner;
import static io.cucumber.junit.platform.engine.Constants.GLUE_PROPERTY_NAME;
import static io.cucumber.junit.platform.engine.Constants.PLUGIN_PROPERTY_NAME;
import org.junit.platform.suite.api.ConfigurationParameter;
import org.junit.platform.suite.api.IncludeEngines;
import org.junit.platform.suite.api.SelectClasspathResource;
import org.junit.platform.suite.api.Suite;
@Suite
@IncludeEngines("cucumber")
@SelectClasspathResource("features")
@ConfigurationParameter(key = GLUE_PROPERTY_NAME, value = "steps")
@ConfigurationParameter(key = PLUGIN_PROPERTY_NAME, value = "pretty, html:target/cucumber-report.html")
public class RunCucumberTest {
}Run all scenarios with mvn test. Run only smoke scenarios with:
mvn test -Dcucumber.filter.tags="@smoke"After the run, open target/cucumber-report.html to see each scenario, its steps and any attached screenshots. If you prefer TestNG as your runner, Cucumber also provides a cucumber-testng module; our TestNG tutorial covers the TestNG side.
Data tables for richer test data
Scenario Outlines repeat a whole scenario for each row. Sometimes you instead need a single step to receive a small table of data, for example to set up several records before a search. Gherkin data tables handle this:
Scenario: Search shows only jobs in the selected city
Given the following jobs exist:
| title | city |
| QA Engineer | Pune |
| SDET | Bangalore |
When I filter jobs by city "Pune"
Then I should see 1 jobThe step definition receives a DataTable, which converts easily to a list of maps:
import io.cucumber.datatable.DataTable;
import io.cucumber.java.en.Given;
import java.util.List;
import java.util.Map;
public class JobSteps {
@Given("the following jobs exist:")
public void theFollowingJobsExist(DataTable table) {
List<Map<String, String>> rows = table.asMaps(String.class, String.class);
for (Map<String, String> row : rows) {
System.out.println("Create job " + row.get("title") + " in " + row.get("city"));
}
}
}In a real suite, that loop would call an API or a test data helper rather than the UI, because creating data through the browser is slow and fragile. Note the {int} parameter in “I should see 1 job”, which Cucumber converts to an integer automatically.
Running scenarios in parallel
As the suite grows, run time becomes a problem. The JUnit Platform engine can run scenarios in parallel. Create src/test/resources/junit-platform.properties:
cucumber.execution.parallel.enabled=true
cucumber.execution.parallel.config.strategy=fixed
cucumber.execution.parallel.config.fixed.parallelism=3
cucumber.execution.parallel.config.fixed.max-pool-size=3Because PicoContainer creates a fresh TestContext for every scenario, each scenario gets its own browser, which is exactly what parallel runs need. Problems usually come from elsewhere: shared test accounts, static fields in helper classes, or scenarios that depend on data created by other scenarios. Fix those before increasing the thread count.
Writing good Gherkin: do and avoid
| Do | Avoid |
|---|---|
| Describe behaviour: “When I apply coupon SAVE10” | Describe clicks: “When I click the button with id applyBtn” |
| One behaviour per scenario | Long scenarios testing five things at once |
| Use Background for shared preconditions only | Hiding important steps in Background |
| Keep scenarios to about 3-8 steps | Twenty-step scripts converted line by line from manual tests |
| Reuse steps through parameters | Creating near-duplicate steps with slightly different wording |
Good scenarios read like acceptance criteria. If a product owner cannot understand a scenario without asking you, rewrite it. Our guide on how to write test cases helps with choosing which examples matter.
Common errors and fixes
- Undefined step: The step text does not match any definition. Cucumber prints a suggested snippet; check spelling, quotes and the glue package.
- Duplicate step definitions: Two methods match the same text. Make each step pattern unique.
- Null driver in steps: State was stored in a static field or a different instance. Use dependency injection as shown.
- Hooks not running: Wrong
@Beforeimport or the hooks class is outside the glue package. - Tests not discovered by Maven: Old Surefire version or missing
junit-platform-suitedependency.
For deeper reference, the official Cucumber documentation covers Gherkin syntax, expressions and runners.
🚀 Looking for BDD automation jobs?
QA Jobs India shares 100+ fresh QA & software testing openings every morning — manual, automation, API and remote roles.
See today’s QA jobs →FAQs
Is Cucumber a testing tool or a BDD tool?
Cucumber is a tool that supports BDD by executing scenarios written in Gherkin. BDD itself is a collaboration practice. Teams can use Cucumber without full BDD, but they lose much of its value.
What is the difference between Scenario and Scenario Outline?
A Scenario runs once with fixed values. A Scenario Outline uses placeholders and an Examples table, running the same steps once per row. Use outlines for data variations of the same behaviour.
Do I need TestNG or JUnit with Cucumber?
You need a runner. The JUnit Platform engine is the currently recommended option, and a TestNG integration is also available. The choice usually follows what the rest of your framework uses.
How do you share data between step definition classes?
Use dependency injection, such as PicoContainer, to inject a shared context object into the constructors of step classes. Avoid static fields, which break parallel execution.
Is Cucumber still in demand for testing jobs in India?
Many job descriptions for Selenium automation roles, especially in banking, insurance and large enterprise projects, mention Cucumber or BDD. It is worth learning alongside a core framework.
Conclusion
Build the project from this Cucumber BDD tutorial, run it, then add one feature of your own with three scenarios written before you write any Java. Ask a non-technical friend to read the feature file; if they can explain what is being tested, your Gherkin is on the right track.
- 100+ fresh QA jobs daily + Direct HR email IDsLive every morning at 9 AM — apply straight to HR
- Weekly Mega Job Fair800+ QA jobs from India & around the world, every week
- Certified QA coursesUp to 3 courses included · all 17 for ₹500
- AI ATS Resume BuilderFree resume points included
- Full LinkedQA feedEvery post, fully unblurred
- Complete QA Material libraryInterview Q&A, cheat sheets, templates & roadmaps
Instant activation right after payment · One login for jobs, courses, resume & LinkedQA
💎 Get every QA opening, every day
Join QA Jobs India Premium for 100+ verified QA jobs daily with HR contact details.