Cucumber Selenium – A Comprehensive Guide

Cucumber-Selenium-A-Comprehensive-Guide.jpg

Cucumber Selenium is widely used in automation testing to combine behavior-driven development with browser automation. Cucumber allows teams to write test scenarios in plain language, while Selenium handles real user interactions in the browser.

In this blog, you will learn what Cucumber Selenium is, why it’s used, how to set it up step by step, and how to write and execute your first automation tests. We’ll also cover practical examples, advantages and disadvantages, and when this framework makes sense for real-world projects.

Table of Contents:

What is Cucumber Selenium?

Cucumber for Selenium is a powerful combination of two popular tools used in automation testing: Cucumber and Selenium. You can create test scenarios using Cucumber, a behavior-driven development (BDD) tool, in a natural-language manner.  It uses a simple and readable syntax called Gherkin, which makes it easier for both technical and non-technical stakeholders to understand and collaborate on testing efforts.

Selenium, however, serves as a widely-utilized open-source automation framework for web applications. It offers an extensive range of APIs and tools to automate browser interactions, allowing testers to replicate user actions like clicking buttons, completing forms, and verifying outcomes.

By combining Cucumber and Selenium, you can create comprehensive and maintainable automated tests. Cucumber acts as a bridge between stakeholders and the automation code, allowing you to express test cases in a business-readable format. Meanwhile, Selenium provides the underlying automation capabilities to execute these test cases on web applications.

Why Use Cucumber with Selenium?

Cucumber with Selenium is widely used because it makes automated testing easier to understand, manage, and scale, without compromising on browser-level automation.

  • Scalable Test Automation: Cucumber and Selenium together support large test suites and integrate well with CI/CD pipelines for continuous testing.
  • Business-Readable Test Scenarios: Cucumber uses Gherkin (Given–When–Then) syntax, allowing test cases to be written in plain English. This makes test scenarios easy for non-technical stakeholders to read and review.
  • Robust Web Automation: Selenium handles browser automation across different browsers and platforms. When integrated with Cucumber, it executes real user actions reliably.
  • Better Team Collaboration: Cucumber enables developers, testers, and business teams to collaborate on a shared test definition. This reduces misunderstandings and improves requirement clarity.
  • Living Documentation: Cucumber feature files act as up-to-date documentation of application behavior. Test reports clearly show scenario status and execution results.
  • Reusable and Maintainable Tests: Step definitions allow test steps to be reused across scenarios. This keeps the automation framework clean and easy to maintain.

Prerequisites for Using Cucumber with Selenium

Before getting started with Cucumber Selenium automation, ensure the following prerequisites are in place:

  1. Programming Language: Cucumber and Selenium support multiple languages such as Java, Python, JavaScript, C#, and Ruby. Choose one based on your team’s expertise and project needs.
  2. Java Development Kit (JDK): If you are using Java with Cucumber and Selenium, installing the JDK is mandatory. Other language bindings do not require Java.
  3. Integrated Development Environment (IDE): An IDE like Eclipse, IntelliJ IDEA, or Visual Studio Code helps with writing, debugging, and managing automation code efficiently.
  4. Selenium WebDriver: Selenium WebDriver is required to automate browser interactions. Install the WebDriver binaries for the browser you intend to test, such as ChromeDriver, GeckoDriver, or EdgeDriver.
  5. Cucumber and Selenium Dependencies: Add the required Cucumber and Selenium libraries to your project using a build tool like Maven or Gradle to manage dependencies and versions smoothly.
  6. Build Tool: Tools like Maven or Gradle are commonly used to structure Cucumber Selenium projects and execute tests consistently.

Get 100% Hike!

Master Most in Demand Skills Now!

Setting up the Environment

Before you start automating tests with Cucumber and Selenium, it’s crucial to ensure your environment is properly set up. Follow these steps:

1. Install Java Development Kit (JDK)

  • Recommended version: JDK 17 or later.
  • Download from the official Oracle website.
  • Install according to your operating system.

2. Configure Environment Variables

Add the JDK bin directory to your system’s PATH so you can run Java commands from any terminal.

  • Windows: Search for “Environment Variables” → Edit PATH → Add C:\Program Files\Java\jdk-17\bin.
  • Mac/Linux: Add export PATH=$PATH:/path/to/jdk/bin to .bashrc or .zshrc.

3. Install an IDE

  • Use Eclipse, IntelliJ IDEA, or Visual Studio Code.
  • These IDEs provide code auto-completion, debugging tools, and Maven/Gradle integration.

4. Add Selenium WebDriver

Install WebDriverManager to automatically manage browser drivers. This avoids manual downloads.

For Maven, add the following dependency in your pom.xml:

<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>5.5.0</version>
</dependency>

5. Set Up Maven Project

  • Create a Maven project in your IDE.
  • Add dependencies for Cucumber, Selenium, and JUnit in your pom.xml:
<dependencies>
    <!-- Cucumber Java -->
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>7.13.0</version>
    </dependency>

    <!-- Cucumber JUnit -->
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>7.13.0</version>
        <scope>test</scope>
    </dependency>

    <!-- Selenium Java -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.11.0</version>
    </dependency>
</dependencies>

6. Verify Your Setup

Create a minimal Java class to open a browser using WebDriverManager:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;

public class SetupTest {
    public static void main(String[] args) {
        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.google.com");
        System.out.println("Title: " + driver.getTitle());
        driver.quit();
    }
}

Run this class. If Chrome opens and displays Google, your environment is ready.

Writing Your First Cucumber Selenium Test

Once the environment is ready, you can start writing your first automated test:

1. Create a Feature File

  • Location: src/test/resources
  • Example (GoogleSearch.feature):
Feature: Google Search
  Scenario: Search for “Cucumber Selenium”
    Given I am on the Google search page
    When I enter “Cucumber Selenium” in the search box
    And I click the search button
    Then I should see results related to “Cucumber Selenium”

2. Write Step Definitions

  • Location: src/test/java/stepdefinitions
  • Example (GoogleSearchSteps.java):
package stepdefinitions;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.cucumber.java.en.*;
import io.github.bonigarcia.wdm.WebDriverManager;

public class GoogleSearchSteps {
    WebDriver driver;

    @Given("I am on the Google search page")
    public void iAmOnTheGoogleSearchPage() {
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
        driver.get("https://www.google.com");
    }

    @When("I enter {string} in the search box")
    public void iEnterInTheSearchBox(String searchTerm) {
        driver.findElement(By.name("q")).sendKeys(searchTerm);
    }

    @When("I click the search button")
    public void iClickTheSearchButton() {
        driver.findElement(By.name("btnK")).click();
    }

    @Then("I should see search results related to {string}")
    public void iShouldSeeSearchResultsRelatedTo(String searchTerm) {
        String pageTitle = driver.getTitle();
        assert(pageTitle.contains(searchTerm));
        driver.quit();
    }
}

3. Run the Test

  • Right-click on the feature file → Run As → Cucumber Feature
  • Observe the browser automation and console output to ensure everything works correctly.

Automation Testing Using Cucumber with Selenium

Once your environment is ready, you can start automation testing using the Cucumber Selenium framework. This approach combines BDD-style test scenarios with powerful browser automation, making tests easy to write, understand, and maintain.

1. Define Test Scenarios

Start by identifying the application behaviors you want to validate. These scenarios should reflect real user actions such as login, form submission, navigation, or search functionality. Clear scenarios ensure your automation aligns with business requirements.

2. Create Feature Files

Cucumber uses feature files written in Gherkin syntax to describe test cases in a human-readable format. Using Given–When–Then, feature files document expected behavior and act as living documentation for your automation tests.

3. Implement Step Definitions

Each step in a feature file is mapped to step definitions, where Selenium WebDriver code is written. These step definitions handle browser interactions such as clicking elements, entering text, and validating results.

4. Execute Automated Tests

Run your Cucumber Selenium tests using a test runner, IDE, or build tool like Maven. During execution, Cucumber reads feature files, matches steps to step definitions, and Selenium performs the browser automation.

5. Analyze Test Results

After execution, Cucumber generates clear test reports showing passed, failed, and skipped scenarios. These reports help teams quickly identify defects and track test coverage.

6. Maintain and Scale Tests

As the application evolves, update feature files and step definitions to reflect changes. Thanks to reusable steps and modular design, the Cucumber Selenium automation framework scales well for large test suites.es test readability, and establishes a robust framework for automation testing.

Advantages and Disadvantages of Cucumber with Selenium

Using Cucumber with Selenium offers several practical benefits, but it also comes with certain trade-offs. Understanding both sides helps you decide whether this combination fits your project needs.

Advantages of Cucumber with Selenium

  • Detailed test reporting: Cucumber generates structured execution reports that help track test results and failures easily.
  • Business-readable tests: Cucumber uses Gherkin syntax (Given–When–Then), making test scenarios easy to read and understand for non-technical stakeholders.
  • Strong collaboration: Developers, testers, and business analysts can work together on feature files, ensuring tests reflect real business requirements.
  • Clear separation of concerns: Feature files define what to test, while step definitions handle how to test it using Selenium.
  • Reusability of test steps: Common steps can be reused across multiple scenarios, reducing duplication and improving maintainability.
  • Powerful browser automation: Selenium handles complex browser interactions, while Cucumber provides structure and readability on top of it.

Disadvantages of Cucumber with Selenium

  • Performance impact: Layering Cucumber on top of Selenium can slightly slow down test execution compared to raw Selenium scripts.
  • Initial setup complexity: Setting up Cucumber, Selenium, dependencies, and project structure requires more effort compared to plain Selenium tests.
  • Additional learning curve: Teams need to understand Gherkin, step definitions, and BDD concepts, which may slow onboarding initially.
  • Overhead for small projects: For simple or short-lived projects, Cucumber may feel excessive compared to lightweight test frameworks.
  • Maintenance overhead at scale: Poorly written or overly generic step definitions can become hard to manage in large test suites.

Examples of Cucumber Selenium

Below are commonly used Cucumber Selenium examples that demonstrate how the framework is applied in real-world automation testing.

Example 1: Basic Cucumber Selenium Test Case

Feature File (Login.feature)

Feature: Login functionality

  Scenario: Successful 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 dashboard

Step Definitions (LoginSteps.java)

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

@When("user enters valid username and password")
public void user_enters_credentials() {
    driver.findElement(By.id("username")).sendKeys("admin");
    driver.findElement(By.id("password")).sendKeys("password");
    driver.findElement(By.id("loginBtn")).click();
}

@Then("user should be redirected to the dashboard")
public void user_is_redirected_to_dashboard() {
    Assert.assertTrue(driver.getCurrentUrl().contains("dashboard"));
}

Example 2: Data-Driven Testing Using Scenario Outline

Feature File with Examples Table

Scenario Outline: Login with multiple credentials
  Given user is on the login page
  When user enters "<username>" and "<password>"
  Then login result should be "<status>"

Examples:
  | username | password | status |
  | admin    | admin123 | success |
  | user1    | wrongpwd | failure |

Cucumber automatically executes the scenario once for each row of test data, enabling efficient data-driven testing without duplicating code.

Conclusion

Cucumber Selenium is a powerful automation testing framework that combines behavior-driven development with reliable browser automation. By using Gherkin-based test scenarios and Selenium WebDriver, teams can create tests that are easy to understand, maintain, and scale.

From setting up the environment to writing feature files, step definitions, and real-world test scenarios, Cucumber Selenium helps improve collaboration, test coverage, and overall automation efficiency. While it may require some initial setup and learning, it remains a strong choice for teams building robust, maintainable automation testing solutions.

Is Cucumber Selenium suitable for beginners?

Yes, Cucumber Selenium can be used by beginners, especially those familiar with basic programming concepts. Cucumber’s Gherkin syntax makes test scenarios easy to read, while Selenium handles browser automation behind the scenes. However, beginners should expect a short learning curve when working with step definitions and framework setup.

Can Cucumber Selenium be used without BDD practices?

Technically, yes. You can use Cucumber with Selenium purely as a test automation framework. However, its real strength comes from following BDD principles, where feature files reflect business behavior and encourage collaboration between teams.

Is Cucumber Selenium good for large enterprise projects?

Yes. Cucumber Selenium scales well for enterprise-level automation when implemented with reusable step definitions, proper project structure, and CI/CD integration. Many large teams use it to manage complex test suites across multiple applications.

Does Cucumber Selenium support parallel execution?

Yes. Cucumber Selenium supports parallel test execution when integrated with tools like TestNG, JUnit, or Maven Surefire. Parallel execution helps reduce overall test runtime, especially in large automation suites.

Can Cucumber Selenium be integrated with CI/CD tools?

Absolutely. Cucumber Selenium integrates smoothly with CI/CD tools such as Jenkins, GitHub Actions, GitLab CI, and Azure DevOps. This enables automated test execution as part of continuous integration and delivery pipelines.

Is Cucumber Selenium limited to web testing?

Primarily, yes. Selenium is designed for web application testing. However, Cucumber can be used with other tools (like Appium or REST-assured) to extend BDD-style testing to mobile and API testing as well.

About the Author

Senior Associate - Automation and Testing

Akshay Shukla, a senior associate at a multinational company, is an experienced professional with a rich background in cloud computing and software testing. He is proficient in frameworks like Selenium and tools like Cucumber. He also specialises in Test-Driven Development and Behavior-Driven Development.