📣 Requestly API Client – Free Forever & Open Source. A powerful alternative to Postman. Try now ->

How to Automate Testing Using Cucumber Framework in Selenium

Rohit Rajpal
Learn how to automate testing with the Cucumber framework in Selenium, including how to set up, write tests, and best practices for efficient test automation.
How to Automate Testing Using Cucumber Framework in Selenium

Cucumber is a popular framework used for Behavior Driven Development in test automation. It allows writing test scenarios in plain English so that both technical and non-technical stakeholders can easily understand them.

When combined with Selenium, Cucumber helps automate web applications while keeping the tests aligned with business requirements. This makes the overall approach more collaborative, structured, and easier to maintain.

This article explains how to automate testing using the Cucumber framework in Selenium in detail.

What Is Cucumber in Selenium

Cucumber is a testing framework that supports Behavior Driven Development (BDD). It allows test cases to be written in a format called Gherkin, which uses simple English phrases like Given, When, and Then. This way, the focus stays on the behavior of the application rather than the technical implementation.

Selenium, on the other hand, is a web automation tool. It interacts with web elements in browsers, executes actions like clicks and typing, and validates outputs. When combined, Selenium handles the browser automation while Cucumber provides the structure and readability for defining the test cases.

This integration helps both testers and business stakeholders. Testers can automate functional flows using Selenium, while stakeholders can review the scenarios in Cucumber without having to read or understand code. This bridge between technical and non-technical teams is what makes Cucumber in Selenium highly valuable for collaborative automation.

Why Use Cucumber in Selenium

Cucumber adds business readability to test automation, while Selenium handles browser-level execution. Together, they create tests that are easy to understand and directly runnable on applications. Below are the main reasons teams adopt this combination:

  • Shared understanding across roles: Test scenarios are written in Gherkin syntax, so business analysts, developers, and testers can all review and agree on them.
  • Traceability of requirements: Each scenario links back to a specific business rule, making it clear which requirement is being validated.
  • Maintainable automation: Separating feature files from code makes it easier to update tests when requirements or application behavior change.
  • Executable documentation: The same scenarios that describe behavior double as automated tests, keeping documentation and automation aligned.
  • Faster feedback: Tests run directly on browsers through Selenium, giving teams immediate insight into whether features work as expected.

How Cucumber Works with Selenium for BDD Testing

Cucumber and Selenium integrate by translating plain-text scenarios into automated browser tests. The process is sequential, where each layer hands off to the next until execution and reporting are complete.

  • Write scenarios in feature files: Teams describe behavior in Gherkin format using Given, When, and Then. These serve as the starting point.
  • Map steps to step definitions: Each scenario step is connected to a Java method (or another supported language). This is where Selenium WebDriver commands are written.
  • Run tests with a runner class: The Cucumber test runner identifies the feature files, matches them with step definitions, and begins execution.
  • Execute browser actions with Selenium: When a step is triggered, the linked WebDriver command runs. For example, when a user clicks login, it executes a driver.findElement().click() action.
  • Generate test reports: After execution, Cucumber compiles the outcomes of each scenario into a structured report, making it easy to track pass/fail status.

Core Components of the Cucumber Framework

Cucumber relies on a set of components that connect plain-text scenarios with automation code. Each part plays a specific role in defining, organizing, and executing tests. Understanding these components is essential before setting up a framework. Below are the main ones explained in detail:

1. Feature Files

Feature files are the starting point of any Cucumber framework. They contain the description of application behavior in a format that business and technical teams can both understand. Each file represents a feature or module of the application, such as login, checkout, or user registration.

Inside a feature file, tests are written in Gherkin syntax. Gherkin uses structured keywords like Feature, Scenario, Given, When, Then, And, and But. These keywords make the scenarios consistent, readable, and easy to follow.

A typical feature file includes:

  • Feature: A high-level description of what is being tested, such as “Login functionality.”
  • Scenario: An individual test case written in plain English. Each scenario covers one flow.
  • Scenario Outline: A template for running the same scenario with multiple sets of data.
  • Examples: Data tables used with scenario outlines to provide different inputs.

Feature files make the automation framework transparent. Stakeholders can read them without needing technical knowledge, while testers can link them to step definitions for execution.

2. Step Definitions

Step definitions act as the bridge between the plain-text steps in a feature file and the actual code that performs browser actions. Each step written in Gherkin syntax is matched to a corresponding method in a step definition file.

These files are typically written in Java (when using Selenium with Cucumber), though other languages like Python, Ruby, or JavaScript are also supported. The methods inside step definitions use regular expressions or annotations to map Gherkin steps.

Key points about step definitions:

  • One-to-one mapping: Each step in the feature file should have a matching method in a step definition class.
  • Reusable steps: Common steps like navigation, login, or logout can be reused across multiple scenarios.
  • Selenium integration: Inside each method, Selenium WebDriver commands are used to interact with the application under test.
  • Glue code location: Step definition files are placed in the package or directory specified in the runner class.

Here’s an example for the login feature file:

				
					public class LoginSteps {

    WebDriver driver;

    @Given("user is on the login page")
    public void user_is_on_the_login_page() {
        driver = new ChromeDriver();
        driver.get("https://example.com/login");
    }

    @When("user enters valid username and password")
    public void user_enters_valid_username_and_password() {
        driver.findElement(By.id("username")).sendKeys("testuser");
        driver.findElement(By.id("password")).sendKeys("password123");
    }

    @When("clicks the login button")
    public void clicks_the_login_button() {
        driver.findElement(By.id("loginBtn")).click();
    }

    @Then("user should be redirected to the homepage")
    public void user_should_be_redirected_to_the_homepage() {
        String expectedUrl = "https://example.com/home";
        Assert.assertEquals(driver.getCurrentUrl(), expectedUrl);
        driver.quit();
    }
}
				
			

Step definitions give Cucumber the ability to turn readable scenarios into executable browser tests. They are the most critical link between plain English descriptions and Selenium automation.

3. Test Runner Files

Test runner files are responsible for triggering the execution of feature files. They connect the scenarios written in Gherkin with the step definitions that contain Selenium code. Without a runner, the framework would not know where to find scenarios or how to execute them.

In Cucumber with Selenium, the runner class is usually written in Java and makes use of JUnit or TestNG. It specifies important configurations like the path of feature files, the package containing step definitions, and the type of reports to generate.

Key responsibilities of test runner files include:

  • Locating feature files: Define the path where Cucumber should look for .feature files.
  • Specifying glue code: Provide the package where step definitions and hooks are stored.
  • Managing reporting plugins: Configure output formats such as HTML, JSON, or JUnit reports.
  • Controlling execution: Use options like tags to run specific sets of scenarios (e.g., smoke or regression tests).
  • Integrating with test frameworks: Work with JUnit or TestNG to execute tests and integrate with CI/CD pipelines.

Here’s an example using JUnit:

				
					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"},
    tags = "@SmokeTest",
    monochrome = true
)
public class TestRunner {
}
				
			

In this example:

  • The features attribute points to the location of .feature files.
  • The glue attribute tells Cucumber where to find step definitions.
  • The plugin option generates readable reports.
  • The tags option allows selective execution of scenarios.

Test runner files ensure smooth coordination between scenarios and Selenium execution, while also giving flexibility to control which tests run and how results are reported.

4. Hooks

Hooks are special methods that allow setup and teardown around scenarios. They run before or after each scenario, making them useful for tasks that need to be repeated consistently.

Common uses of hooks include:

  • Browser management: Launching a browser before a scenario and closing it after execution.
  • Test data setup: Creating or cleaning up test data before and after runs.
  • Screenshots on failure: Capturing the browser state when a test fails for debugging.

Here’s an example:

				
					import io.cucumber.java.Before;
import io.cucumber.java.After;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Hooks {
    WebDriver driver;

    @Before
    public void setUp() {
        driver = new ChromeDriver();
        driver.manage().window().maximize();
    }

    @After
    public void tearDown() {
        driver.quit();
    }
}
				
			

Hooks make scenarios independent and repeatable by ensuring every test starts and ends with a clean state.

5. Tags

Tags provide a way to organize and control which scenarios should run. They are placed above scenarios or features in the feature file.

Typical use cases include:

  • Grouping tests: Mark scenarios as @SmokeTest, @Regression, or @Critical.
  • Selective execution: Run only a subset of scenarios by specifying tags in the runner.
  • CI/CD integration: Trigger different sets of tests for different stages of the pipeline (e.g., smoke on every commit, regression on nightly builds).

Example feature file with tags:

				
					@SmokeTest
Scenario: Verify login with valid credentials
  Given user is on the login page
  When user enters valid username and password
  Then user should be redirected to the homepage
				
			

Tags make large test suites manageable by providing flexibility in execution.

6. Reports

Cucumber generates detailed reports after test execution. These reports act as living documentation of the application’s behavior and test status.

Common report formats include:

  • HTML reports: Easy to read, providing a summary of passed, failed, and skipped scenarios.
  • JSON reports: Useful for integration with reporting dashboards or CI tools.
  • JUnit or XML reports: Commonly used to integrate with CI/CD pipelines and test management tools.

Teams often extend Cucumber’s reporting by integrating with tools like Allure Reports or ExtentReports, which provide advanced dashboards, screenshots, and analytics.

For example, configuring plugins in the runner:

				
					@CucumberOptions(
    plugin = {"pretty", "html:target/cucumber-html-report", "json:target/cucumber.json"}
)
				
			

Reports give teams a clear view of execution results, help with root cause analysis, and serve as up-to-date documentation for stakeholders.

Setting Up the Cucumber BDD Framework for Selenium

Before writing tests, the framework must be properly set up. This involves installing dependencies, configuring project structure, and preparing the environment for execution. A well-structured setup ensures maintainable and scalable test automation.

Follow these steps to set up the framework:

1. Create a Maven or Gradle project

Use a build tool to manage dependencies and project structure. Maven is widely used for Java-based Selenium and Cucumber projects.

2. Add required dependencies

Include Selenium WebDriver, Cucumber Java, Cucumber JUnit, and any reporting plugins in the pom.xml or build.gradle. For example, a Maven dependency for Cucumber:

				
					 <dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>8.0.0</version>
    <scope>test</scope>
</dependency>
				
			

3. Organize project structure

Typically, the project is divided into features (feature files), step definitions (step code), runners (test runners), and resources (test data or configurations).

4. Set up test runner and reporting

Create runner classes specifying feature locations, glue code, tags, and reporting plugins. This ensures smooth execution and readable results.

5. Integrate with IDE or CI tools

Configure the project to run from an IDE like IntelliJ or Eclipse, or integrate with CI/CD pipelines like Jenkins for automated execution.

Prerequisites for Using Cucumber with Selenium

Before starting the setup, ensure the following technical requirements are in place:

  • Java or supported language installed: Required for step definitions and runner files.
  • IDE ready: IntelliJ IDEA or Eclipse with Maven/Gradle support.
  • Browser drivers configured: ChromeDriver, GeckoDriver, or other WebDriver executables.
  • Dependencies included: Selenium WebDriver, Cucumber, JUnit/TestNG, and reporting plugins.
  • Optional integration tools: CI/CD pipelines (Jenkins) or reporting tools (Allure, ExtentReports) for larger projects.

These prerequisites provide a ready-to-use environment and reduce setup errors, allowing testers to focus on building and running automated tests.

Writing Your First Test in Cucumber for Selenium

Once the framework is set up, the next step is creating and executing a test scenario. Writing your first test helps verify that the framework is configured correctly and that Selenium can automate the browser as expected.

Steps to write your first test:

1. Create a feature file:

Write a .feature file in the features folder. Use Gherkin syntax with Feature, Scenario, Given, When, and Then. 

2. Write step definitions

Map each Gherkin step to a Java method in a step definition file. Use Selenium WebDriver commands to perform actions like clicking, typing, or validating results.

3. Create a test runner class

Configure a runner class that links the feature file and step definitions. Include reporting plugins and specify tags if needed.

4. Run the test

Execute the runner class from your IDE or through the command line. Verify that the browser opens, the steps are executed, and the scenario passes or fails as expected.

5. Validate results

Check the generated Cucumber report for scenario status. Ensure that the test behaves as intended and troubleshoot any failures by reviewing step definitions or browser interactions.

Writing this first test confirms that the framework is working correctly and lays the foundation for adding more scenarios. It also demonstrates how feature files, step definitions, and test runners work together to automate tests effectively.

Best Practices for Cucumber Testing in Selenium

Following best practices ensures that Cucumber tests remain maintainable, reliable, and scalable.

  • Keep scenarios short and focused: Each scenario should test a single behavior or flow. Avoid combining multiple test cases into one scenario to make debugging easier.
  • Reuse step definitions: Common actions like login, logout, or navigation should be written once and reused across scenarios. This reduces duplication and improves maintainability.
  • Use descriptive scenario names: Clear, meaningful scenario titles help stakeholders understand what each test validates without reading the steps.
  • Leverage Scenario Outlines and Examples: For data-driven testing, use scenario outlines with example tables instead of duplicating similar scenarios. This makes tests cleaner and easier to manage.
  • Organize features and step definitions logically: Group related feature files and step definitions in a consistent folder structure to simplify navigation and maintenance.
  • Implement hooks for setup and teardown: Use @Before and @After hooks to initialize and clean up the browser or test data. This ensures that each scenario starts with a clean state.
  • Run tests on real browsers and devices: Applications can behave differently across browsers, screen sizes, and devices. Cloud platforms like BrowserStack allow running Cucumber tests across multiple browsers and real devices simultaneously to accelerate testing while increasing coverage and confidence in results.

Conclusion

Implementing a Cucumber and Selenium framework offers a structured approach to Behavior-Driven Development (BDD), enabling teams to write tests in natural language that stakeholders can easily understand. This bridges the gap between business requirements and technical implementation and ensures that automated tests align closely with user expectations.

For comprehensive testing, validate on real devices to capture device-specific behaviors. BrowserStack’s Real Device Cloud provides access to over 3,500 iOS and Android devices, supports multi-device testing, and handles workflows like biometric authentication and SIM testing, ensuring apps work seamlessly across real-world scenarios.

Written by
Rohit Rajpal
Rohit Rajpal is a B2B Content Strategist at BrowserStack, helping SaaS brands build AI-first strategies that drive authority and revenue. He writes about content, strategy, and the future of search in the zero-click era.

Related posts