The site that you are currently viewing is a static version of the Software Factory documentation delivered with the

version v7.2.
For up-to-date documentation, see the latest version.

Gherkin tests in Java

How to implement a BDD approch for a Java project

Introduction

In this guide, we’ll walk you through using Gherkin for behavior-driven development (BDD) tests for a Maven project in GitLab.

We’ll start from a use case or a new feature request, write Gherkin scenarios, implement step definitions, and integrate these tests into GitLab CI/CD.

Step 1: Capture the Use Case or New Feature Request

  1. Define the Use Case:

    • Begin with a use case or new feature request from the stakeholder. For example, a new feature request for a “User Login” functionality:

      As a registered user,
      I want to log in to the application
      So that I can access my dashboard.
      
  2. Convert Use Case to Gherkin Scenarios:

    • Use the use case to write Gherkin scenarios that describe the expected behavior of the application using the “Given-When-Then” format.

      Feature: User login
      
        Scenario: Successful login with valid credentials
          Given the user is on the login page
          When the user enters credentials with "user" and "password"
          Then the user should be redirected to the dashboard
      
        Scenario: Unsuccessful login with invalid credentials
          Given the user is on the login page
          When the user enters credentials with "user" and "pswd"
          Then the user should see an error message
      

Step 2: Set Up the Project for BDD with Maven

  1. Add Dependencies to pom.xml:

    • Add the necessary BDD testing framework dependencies. For a Java project using Cucumber, update your pom.xml file:

      <dependencies>
          <!-- Cucumber dependencies -->
          <dependency>
              <groupId>io.cucumber</groupId>
              <artifactId>cucumber-java</artifactId>
              <version>7.0.0</version>
              <scope>test</scope>
          </dependency>
          <dependency>
              <groupId>io.cucumber</groupId>
              <artifactId>cucumber-junit</artifactId>
              <version>7.0.0</version>
              <scope>test</scope>
          </dependency>
          <!-- JUnit dependencies -->
          <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <version>4.13.2</version>
              <scope>test</scope>
          </dependency>
      </dependencies>
      
  2. Store Gherkin Scenarios:

    • Save the Gherkin scenarios in .feature files within your project repository. For example, under src/test/resources/features:

      /project-root
        /src
          /test
            /resources
              /features
                user_login.feature
      

Step 3: Implement Step Definitions

  1. Write Step Definitions:

    • Implement step definitions that map Gherkin steps to Java code. For example:

      import io.cucumber.java.en.Given;
      import io.cucumber.java.en.When;
      import io.cucumber.java.en.Then;
      import static org.junit.Assert.assertEquals;
      
      public class LoginSteps {
          @Given("the user is on the login page")
          public void theUserIsOnTheLoginPage() {
              // Code to navigate to the login page
          }
      
          @Then("the user should be redirected to the dashboard")
          public void theUserShouldBeRedirectedToTheDashboard() {
              // Code to assert redirection
              assertEquals("dashboardPage", getCurrentPage());
          }
      
          @When("When the user enters credentials with {string} {string}")
          public void theUserEntersInvalidCredentials(String usr,String pwd) {
              // Code to input invalid credentials
          }
      
          @Then("the user should see an error message")
          public void theUserShouldSeeAnErrorMessage() {
              // Code to assert error message
              assertEquals("Invalid credentials", getErrorMessage());
          }
      }
      
  2. Create Test Runner:

    • Create a test runner class to execute the Cucumber tests:

      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")
      public class CucumberTestRunner {
      }
      

Step 4: Integrate Gherkin Tests into GitLab CI/CD

  1. Create .gitlab-ci.yml File:

    • Define your CI/CD pipeline to run the automated BDD tests. Here’s a basic example:

      image: maven:3.6.3-jdk-11
      stages:
        - build
        - test
      
      build:
        stage: build
        script:
          - mvn compile
        artifacts:
          paths:
            - target/
      
      test:
        stage: test
        script:
          - mvn test
        artifacts:
          when: always
          reports:
            junit:
              - target/surefire-reports/*.xml
          paths:
            - target/surefire-reports/
      
  2. Configure Environment:

    • Ensure your CI environment is configured with the necessary tools and dependencies to run BDD tests. Use Docker images, install dependencies, or configure service containers as needed.
  3. Commit and Push Code:

    • Commit and push your code to the GitLab repository. GitLab CI will automatically trigger the pipeline and execute the defined stages, running the Gherkin scenarios as part of the test stage.

Tips and best practices 🚧

  • Don’t use steps that combine a bunch of different things,
  • DRY (don’t repeat youself) by using parameterization to reuse steps
  • Keep test fast and isolated from external dependencies
  • Use Background to Set Context to avoid repeating the same setup steps in multiple scenarios.