Getting Started with Cucumber BDD Framework in Java (with Maven & Selenium)
Introduction
BDD (Behavior Driven Development) is a software development approach that emphasizes collaboration among stakeholders—including business analysts, developers, and testers—by allowing test cases to be written in plain English using the Gherkin language. This ensures that everyone involved can understand and contribute to the requirements and test scenarios.
In traditional development approaches like TDD (Test Driven Development), Business Analysts (BAs) typically provide Business Requirement Specifications (BRS) at the beginning of the project. Communication tends to be limited after that point, with more focus placed on architecture, tools, resources, and timelines. This often leads to misunderstandings and a lower chance of delivering exactly what the client needs.
BDD addresses these limitations by making continuous communication a core part of the process. The behavior of the application becomes the top priority. All stakeholders—BAs, developers, and testers—collaborate throughout the project to define the expected behavior of the system. This is done through feature files, which describe requirements in a human-readable format.
As a result, BDD increases the chances of delivering a product that meets actual business needs.
What is Cucumber?
Cucumber is a popular tool that supports the implementation of BDD. It enables writing executable specifications in Gherkin syntax, allowing plain-language descriptions to be linked directly to test automation code. This helps ensure that automated tests are always aligned with the business requirements.
Prerequisites
Install
1.JDK Java Development Kit (version 8 or higher)
2.IDE Integrated Development Environment- IntelliJ IDEA/Eclipse/VS Code
3.Appache Maven
4.Cucumber for Java plugin installed .
Project Setup
Step 1: Create a Maven Project in Eclipse
Open Eclipse IDE
Go to File → New → Other...
In the "Select a wizard" dialog, type and select Maven Project
Click Next
On the next screen, check the box labeled:
✔ Create a simple project (skip archetype selection)
Click Next to proceed
Step 2: Enter Project Coordinates (Group ID & Artifact ID)
After selecting Maven Project and proceeding to the next screen:
Fill in the following required fields:
1.Group Id
2.Artifact Id
In Maven (a build automation tool used primarily for Java projects), the group Id and artifact Id are key identifiers for a project. They help define where your project lives and what it's called.
After Clicking "Finish"
Maven will generate the basic project structure:
JRE System Library [project uses Java run time]
Target folder [which contains compiled code and build output]
Pom.xml [The core Maven configuration file where you define dependencies, plugins, and project settings]
Once the Maven project is created, the default folder structure will look like this:

Convert Your Maven Project to Cucumber BDD Framework
Step 3: Add Cucumber & Selenium Dependencies
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>7.22.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.20.0</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>7.21.1</version>
</dependency>Cucumber-java – It gives core Annotations @Given,@When,@Then and helps in mapping Gherkin steps from .feature files to Java methodsin step definition.
Selenium-java- This library gives WebDriver classes like Chrome driver, Firefox Driver etc , Browser options like Chrome Browser, Edge Browser and WebElement Interactions(eg: sendKeys,click).
Cucumber-testng -This integrates Cucumber with the TestNG testing framework.
Step 4: Add the Feature File
Add feature file Under src/test/resources with .feature extention
@tag
Feature: Login
@tag1
Scenario: Launch login
Given user is in login page
When user enter credential
And User clicks login
Then user is in home page
A feature file is a simple text file written in Gherkin language that describes the application's behavior in a human-readable format. It acts as a bridge between business logic and teest implementation.
Tags
@tag - Applies to the entire feature.
@tag1 -A scenario-specific tag, useful for filtering test execution.
Structure of a Feature File
A feature file typically contains:
Feature: – Describes the functionality or part of the application under test.
Scenario-Represents a specific test case or user behavior example.
Steps- Defined using key word
Given – Precondition or starting point
WHEN-Action performed by the user
Then – Expected outcome
And / But – Additional conditions or actions
Step mapping:
Each step in the feature file should have a corresponding method in the Step Definition class, mapped using annotations like @Given, @When, and @Then.
Step 5: Implement Step definition
A Step Definition is a piece of code that links each step in your feature file to the actual automation logic written in Java.
It uses annotations like @Given, @When, and @Then (provided by cucumber-java) to bind human-readable Gherkin steps to executable methods.
Sample step definition looks like below for the above sample feature
@Given("user is in login page")
public void user_in_url() {
login.getLoginPage();
}
@When("user enter credential")
public void user_enter_credential() {
login.enterUserName("practice");
login.enterPassword("SuperSecretPassword!");
}
@When("User clicks login")
public void user_clicks_login() throws InterruptedException {
login.clickLogin();
}
@Then("user is in home page")
public void user_is_in_home_page() {
Assert.assertEquals("Hi, practice!", login.text());
}
Annotation @Given,@When,@Then comes from cucumber-java. Step definition can reuse across multiple scenarios. The text inside the annotation must match exactly with the step in the feature file for it to be recognized and executed
Step 6: Implementing PageFactory with Page Object Model (POM)
PageFactory is part of Selenium’s Page Object Model that helps manage web elements efficiently. Instead of locating elements repeatedly in your test methods, you define them once using annotations like @FindBy.
In traditional approach
WebElement username = driver.findElement(By.id("username"));In PageFactory Approach:
@FindBy(id = "username")
WebElement username;
These elements are initialized in the constructor of the page class:
public LoginPageFactory() {
DriverFactory.initializeDriver("Chrome");
this.driver = DriverFactory.getDriver();
PageFactory.initElements(driver, this);
}
Now, all the web elements and their actions can be reused cleanly across steps.
Step 7:Setting Up Hooks (Setup & Teardown)
Instead of opening the browser, navigating to the page, or closing the browser in every scenario step, we use Cucumber Hooks to run code before and after each scenario or step.
Example
package hooks;
import driverfactory.DriverFactory;
import io.cucumber.java.After;
import io.cucumber.java.Before;
public class Hooks {
@Before
public void driverSetUp() {
DriverFactory.getDriver();
}
@After
public void tearDown() {
DriverFactory.quitDriver();
}
}
Step 8: Implement DriverFactory – Managing WebDriver Instances
The DriverFactory is a utility class designed to manage and provide WebDriver instances (like ChromeDriver, FirefoxDriver, etc.) in a clean and centralized way.
This approach helps in
A single reusable instance of WebDriver across Hooks, Step Definitions, and Page Classes.
package driverfactory;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DriverFactory {
private static WebDriver driver;
private static final Logger logger=LoggerFactory.getLogger(DriverFactory.class);
public static void initializeDriver( String browserType) {
if (driver == null) {
if("Chrome".equalsIgnoreCase(browserType)) {
driver = new EdgeDriver();
}else {
driver = new ChromeDriver();
}
driver.manage().window().maximize();
}
logger.info("Driver Initialized");
}
public static WebDriver getDriver() {
logger.info("getDriver");
return driver;
}
public static void quitDriver() {
if (driver != null) {
driver.quit();
driver = null;
}
logger.info("quitDriver");
}
}
Step 9:Create the Cucumber Test Runner
It is a java class that executes scenarios and it is the entry point to project .It act as glue to connect featurefile, stepdefenition, hooks tags and plugin.
package runner;
import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;
@CucumberOptions(
features="src/test/resources/login.feature",
glue={"stepdefenition",
"hooks"},
plugin={"pretty","html:target/cucumber-Report.html",
"json:target/Report.json"},
tags="@tag1")
public class TestRunner extends AbstractTestNGCucumberTests{
}Cucumber integrates with TestNG to control test execution and generate reports.
@CucumberOptions: Provides configuration to Cucumber for locating feature files, step definitions, hooks, and reporting.
glue: Packages containing step definitions and hooks.
plugin: Defines output format (e.g., HTML report).
Once the runner is set up, you can:
Right-click on the runner file and choose Run to execute all scenarios.
Report
In Cucumber, a "normal report" usually refers to the basic built-in HTML report generated via the html plugin. It's simple, quick to set up, and gives a visual overview of test execution without needing third-party tools.
By default, Cucumber generates a basic HTML report under target folder when using the plugin option in runner class
"pretty","html:target/cucumber-Report.html"
This normal report includes
1.Pass/fail status
2.Total scenarios run
3.Execution time
Cucumber generates a JSON-formatted report in the target/Report.json location when using the below plugin option in runner class
plugin={"json:target/Report.json"}JSON format is Machine-readable format which can be parsed by other tools .
And is used for
Integrating with CI/CD tools(like Jenkin)
Generating advanced reports using plugins like Cucumber Reports, ExtentReports, or Allure.
The project structure after completing the setup will look like this:

Conclusion
Behavior Driven Development (BDD) is a powerful approach that bridges the communication gap between business stakeholders, developers, and testers by writing test scenarios in plain English. Using Cucumber with Java, Selenium, and Maven provides a scalable and maintainable test automation framework.
Here we learned
How to configure a Maven project.
Create and map feature files to step definitions.
Set up runner classes and hooks for browser control.
Generate useful reports in both HTML and JSON formats.
Thanks for reading the blog! Hope you found it helpful—happy learning and best of luck on your coding journey!


