Cucumber BDD with Java - Selenium Framework

What is BDD?

BDD, or Behavior-Driven Development, is a collaborative approach for software teams that bridges the communication between business and technical professionals. It achieves this by:

  • Fostering collaboration across different roles to cultivate a collective comprehension of the issue.
  • Embracing swift, incremental iterations to enhance feedback loops and value delivery.
  • Generating system documentation that undergoes automatic validation against the system's actual behavior.

Installation of JAVA & Eclipse:

Add Dependencies

  • Set the Java home path and bin path in the system environment variables

Add the Dependencies in Pom.xml

Go to Help > Install new software > paste this link.

Install New Software

  • Accept the terms and conditions and click on finish, Restart the Eclipse

Install Cucumber Plugins

  • Go to Eclipse Marketplace > search cucumber > install cucumber plugin.

Search Cucumber And Install

  • Accept the terms and conditions and restart the Eclipse.

Convert the Maven project to the Cucumber Project:

  • Right-click on project > configure > convert to cucumber project.

Convert To Cucumber Project

What is Gherkin syntax?

  • "Gherkin uses a set of special keywords to give structure and meaning to executable specifications. In the Gherkin language, lines mostly start with these keywords."
  • The primary/Widely used keywords in Gherkin are listed below:
  • Feature, Scenario, Given, When, Then, And, But, Example.
  • Feature - In the feature, we can describe the module, like on which module we are working or creating the feature file.
  • Scenario - In the Scenario, we are describing our TC or scenario.
  • Given - The given keyword describes the initial context (Prerequisites).
  • When - When a keyword is used to describe the Action.
  • Then - In Then, we add the Expected result or what we expect.
  • And, But: Used to combine multiple Given, When, or Then steps.
  • Example -Provides a table of inputs to a Scenario Outline

Feature File

  • A feature file is a common file used to store features and scenarios. It serves as the entry point for writing Cucumber tests.
  • The extension of the feature file is ".feature". Each functionality of the application must have a separate feature file. Multiple feature files can be created, but all must have the ".feature" extension.

Feature File

StepDefination File

  • A Step Definition is a method with an expression that links it to one or more Gherkin steps. When Cucumber executes a Gherkin step in a scenario, it will look for a matching step definition to execute.
  • How to create a StepDefination file :
  • create feature files using Gherkin syntax.
  • Right-click on feature file > Run As > Run configuration

Step Definition File Configuration

  • Click on the Cucumber feature > New configuration > Browse project from local > copy the feature file path > Run
  • Cucumber will create a step definition file for unimplemented steps in the feature file.

Cucumber Create Manage And Run Configuration

implement-missing-steps-with-snippets.webp

  • Copy the unimplemented missing steps from the console and add them to the step definition file.

Cucumber Missing Step Files

TestRunner file using Junit

  • TestRunner class provides the link between the feature file and the step definition file.
  • The RunWith annotation commands run the specified class instead of the created JUnit class.
  • The CucumberOptions annotation specifies different options for the Cucumber test.

Different Options With Junit

Test Runner file using TestNG

  • In the TestNG test runner class, we have to extend the runner class with AbstractTestNGCucumberTests
  • For the TestNG runner class, we are not including @RunWith(Cucumber.class)

Testrunner Testing

Cucumber Scenarios

Cucumber scenarios represent individual test cases written in Gherkin syntax, a human-readable format. They outline specific behaviors or functionalities to be tested within an application. Each scenario consists of a series of steps, including Given, When, and Then, which describe the initial context, the action being performed, and the expected outcome, respectively.

Scenario Outline and Parameterization

A scenario outline is used for parameterization. It allows you to run the same scenario multiple times with different test data sets. Let us understand with the example below.

Example:

Feature: Verify the login functionality

Scenario Outline: Login with Username and password.

Given I open the Chrome browser

    And I navigate to the login page.

    When I click on the login button.

    And I provide username as <Username> and password as <Password>

    And I click on the login button.

    Then Login success window should be displayed.

Examples:

      | Username                    | Password |

      | test@gmail.com     | *****    |

      | test@mailinator.com | *****    |

      | test@outlook.com | *****    |

scenario outline

Cucumber hooks

Cucumber hooks are blocks of code designed to run before or after specific scenarios or steps. They prepare or clean up test environments, initialize variables, and execute other routine tasks in automated testing. Below are examples illustrating the utilization of Cucumber hooks:

  1. Before Hook: This hook runs in a feature file before each Scenario.
  2. After Hook: This hook runs in a feature file after each Scenario.

Cucumber Hooks

Cucumber plugins

Cucumber allows you to extend its functionality by using plugins. These plugins provide additional features and reporting options to enhance your test automation.

  1. Pretty Plugin: This plugin prints the feature files in a human-readable format to the console.

Pretty Plugin

  1. HTML Plugin: It generates an HTML report with the results of your Cucumber tests.

Html Plugin

  1. JUnit Plugin: This plugin generates JUnit XML reports, which can be integrated with CI/CD tools.

Junit Plugin

Cucumber Reports

Cucumber Reports provide comprehensive documentation and insights into the execution of Cucumber tests. These reports summarize test results clearly, including passed, failed, and pending scenarios.

1.HTML Reports:

Cucumber's built-in HTML formatter generates easy-to-read HTML reports. You can use the --plugin html:target/cucumber-reports option to specify the output directory for HTML reports. The generated HTML report will include information about passed and failed scenarios, step definitions, and more.

2.JSON Reports:

Cucumber can generate JSON reports that provide structured data about the test results. Use the --plugin json:target/cucumber-reports/cucumber.json optionto generate a JSON report. JSON reports can be useful for custom reporting or integration with other tools.

3.JUnit XML Reports:

Cucumber can produce JUnit XML reports, which are commonly used in Continuous Integration (CI) pipelines. Usethe --plugin junit:target/cucumber-reports/cucumber.xml option to generate JUnit XML reports. CI tools like Jenkins can parse JUnit XML reports to display test results.

4. Custom Reports:

Extend the ‘cucumber.api.formatter.Formatter’ class and implement the required methods to define your custom reporting format. Use the --plugin option to specify your custom formatter.

Cucumber parallel execution

Cucumber parallel execution enables the simultaneous running of Cucumber scenarios, substantially reducing the overall test execution time. This capability proves particularly beneficial for extensive test suites, where sequential execution can be notably time-intensive. To implement parallel execution with Cucumber, you can proceed with the following general steps:

1. Configure Your Testing Environment:

Ensure that your testing environment (e.g., Selenium Web Driver, database connections, etc.) is thread-safe, as multiple threads will access it concurrently during parallel execution.

2. Split Your Features:

Divide your feature files into multiple sets to be executed in parallel. You can organize them into directories or use tags to group features that can run concurrently.

3. Create Multiple Test Runners:

Create multiple test runner classes, each responsible for running a subset of your features. Depending on your programming language, you can use parallel test execution libraries or frameworks like TestNG (Java) or others to manage parallel execution.

4. Configure Parallel Execution:

Specify the number of parallel threads or processes you want to run concurrently. Configure your test runners to execute in parallel. The exact configuration may vary based on the testing framework you are using.

*Here's an example of how to achieve parallel execution with Cucumber in Java using JUnit and Maven:

Maven Configuration:

In your Maven pom.xml file, you can use the maven-surefire-plugin to configure parallel execution and specify the test runners.

Maven Configuration

Create a Test Runner for Parallel Execution

Create multiple test runner classes, each annotated with @RunWith(Cucumber.class) specifying the features and glue paths and add tag = @parallel.

Test Runner For Paralled Execution

Conclusion

Cucumber is a powerful tool for behavior-driven development, promoting collaboration between business and technical teams. Its structured Gherkin language facilitates clear and executable specifications. Cucumber's ability to run tests in parallel optimizes test suite execution, saving valuable time. By utilizing Cucumber hooks and step definitions, testers can streamline test setup and maintenance. Cucumber empowers teams to create robust, understandable, and efficient automated tests, enhancing software quality and accelerating development cycles.

About Author

Sachin PawarSachin Pawar is a proficient Quality Executive at the Pixel QA, where he ensures top-notch quality in software products and services. His journey in the IT industry commenced in 2019 as a Software Test Engineer, and he has been making remarkable progress ever since. His long-term vision is to ascend to the QA Lead or QA Consultant role to shape the quality assurance landscape.

Beyond his professional life, Sachin enjoys playing cricket, exploring unknown destinations with friends, and seeking adventure through trekking.