Software Testing & Quality

Behaviour-Driven Development with Cucumber and Gherkin

Intermediate7 min readUpdated

BDD is a way of agreeing on what to build before anyone writes code; Cucumber is one way of recording that agreement so it stays true. This guide covers the discovery conversation, the Gherkin syntax in detail, wiring scenarios to Java step definitions, and the failure modes that turn a feature suite into a maintenance burden.

What you will learn

  • Run a discovery conversation that produces concrete examples before code exists
  • Write Gherkin that describes business behaviour rather than user-interface steps
  • Implement step definitions in Java and share state between them safely
  • Use Scenario Outline, Background, tags and hooks without duplicating scenarios
  • Recognise the anti-patterns that make a Cucumber suite slow, brittle and unread

Most defects that matter are not coding mistakes. They are misunderstandings: the developer built what the ticket said, the ticket said what the analyst understood, and the analyst understood something slightly different from what the business meant. Behaviour-driven development is a set of practices aimed squarely at that gap, and its central technique is disarmingly simple — before writing code, get the people with different perspectives into one conversation and force them to agree on concrete examples.

Cucumber enters afterwards. It takes those examples, written in a structured natural language called Gherkin, and executes them against the system so that the agreement cannot silently rot. That automation step is genuinely useful and also the part most likely to be adopted without the conversation, which is how teams end up with a thousand slow, brittle feature files that nobody outside the team has ever opened.

Discovery before automation

The conversation has a shape. Take one user story, put a product person, a developer and a tester in front of it for half an hour, and work through it with example mapping: the story on one card, each business rule it implies on another, concrete examples under each rule, and questions nobody present can answer on a fourth colour.

What comes out is rarely the examples. It is the questions. "What happens if the customer is a premium member and the order is international?" "Does a partial refund reset the return window?" Each question found in that room is a defect that was never written, and the number of question cards is a decent signal of whether the story is ready: none usually means the rules were not examined; many means the story should go back to be split or clarified.

The examples that survive become the acceptance criteria. Some are automated as scenarios; many are better covered by a unit test; a few describe things not worth automating at all. Choosing which is which is a judgement call, and getting it wrong in the direction of "automate everything through Cucumber" is the most common way this practice fails.

Gherkin, precisely

A .feature file is plain text with a small keyword set. Each file holds one feature; each scenario is one example of the behaviour.

Feature: Free shipping thresholds
  So that customers are encouraged to fill their basket,
  orders qualify for free shipping under published rules.

  Background:
    Given the free shipping threshold is 50 EUR

  Scenario: An order above the threshold ships free
    Given a basket containing:
      | product   | quantity | unit price |
      | Notebook  | 2        | 24.00      |
      | Pencil    | 1        | 3.50       |
    When the customer requests domestic delivery
    Then the shipping cost is 0.00 EUR

  Scenario: An order below the threshold pays standard shipping
    Given a basket containing:
      | product   | quantity | unit price |
      | Pencil    | 4        | 3.50       |
    When the customer requests domestic delivery
    Then the shipping cost is 4.90 EUR

  Scenario Outline: Premium members ship free regardless of basket value
    Given a <tier> customer with a basket worth <value> EUR
    When the customer requests domestic delivery
    Then the shipping cost is <cost> EUR

    Examples:
      | tier     | value | cost |
      | premium  | 10.00 | 0.00 |
      | premium  | 60.00 | 0.00 |
      | standard | 10.00 | 4.90 |
      | standard | 60.00 | 0.00 |

The keywords do specific jobs. Given establishes context — state that already exists, never an action the user performs. When is the single event under test; a scenario with three When steps is really three scenarios or a badly chosen event. Then asserts an observable outcome, and it must be observable to the actor in the scenario: "then the row in the orders table has status PAID" is a developer's assertion dressed in Gherkin. And and But continue the previous keyword and exist purely for readability.

Background holds Given steps common to every scenario in the file. It is easy to abuse: a background of eight steps means every scenario carries setup that most of them do not need, and the reader has to hold it all in mind. Keep it to one or two steps of genuinely universal context.

Scenario Outline with an Examples table runs the same scenario once per row — the right tool when one rule has several illustrative cases, and the wrong tool for enumerating twenty boundary values, which belong in a parameterised unit test.

Data tables (the pipe-delimited block under a step) and doc strings (triple-quoted text) pass structured arguments to a step. Tags (@smoke, @slow, @wip) placed above a feature or scenario select what runs; the pipeline can then run @smoke on every commit and everything nightly.

Wiring scenarios to Java

Cucumber matches each step line against annotated methods. The current syntax uses Cucumber Expressions, which are far more readable than the regular expressions older projects used:

public class ShippingSteps {

    private final ShoppingContext context;      // shared state, injected

    public ShippingSteps(ShoppingContext context) {
        this.context = context;
    }

    @Given("the free shipping threshold is {bigdecimal} EUR")
    public void theThresholdIs(BigDecimal threshold) {
        context.pricing().setFreeShippingThreshold(Money.of(threshold, "EUR"));
    }

    @Given("a basket containing:")
    public void aBasketContaining(DataTable table) {
        for (Map<String, String> row : table.asMaps()) {
            context.basket().add(
                    row.get("product"),
                    Integer.parseInt(row.get("quantity")),
                    Money.of(row.get("unit price"), "EUR"));
        }
    }

    @Given("a {word} customer with a basket worth {bigdecimal} EUR")
    public void aCustomerWithABasketWorth(String tier, BigDecimal value) {
        context.setCustomer(new Customer(Tier.valueOf(tier.toUpperCase(Locale.ROOT))));
        context.basket().add("Assorted", 1, Money.of(value, "EUR"));
    }

    @When("the customer requests {word} delivery")
    public void theCustomerRequestsDelivery(String destination) {
        context.setQuote(context.shipping().quote(
                context.basket(), context.customer(), Destination.valueOf(destination.toUpperCase(Locale.ROOT))));
    }

    @Then("the shipping cost is {bigdecimal} EUR")
    public void theShippingCostIs(BigDecimal expected) {
        assertThat(context.quote().shippingCost()).isEqualTo(Money.of(expected, "EUR"));
    }
}

Built-in parameter types cover {int}, {word}, {string}, {float} and {bigdecimal}; you register your own with @ParameterType so that {money} or {tier} arrives as a domain object rather than a string, which removes most of the parsing noise from step methods.

The runner on JUnit 5 uses the platform engine, configured either through the suite API or junit-platform.properties:

@Suite
@IncludeEngines("cucumber")
@SelectClasspathResource("features")
@ConfigurationParameter(key = GLUE_PROPERTY_NAME, value = "com.example.shop.acceptance")
@ConfigurationParameter(key = FILTER_TAGS_PROPERTY_NAME, value = "not @wip")
@ConfigurationParameter(key = PLUGIN_PROPERTY_NAME, value = "pretty, html:target/cucumber-report.html")
public class RunAcceptanceTests {
}

Sharing state without a static field

Step definitions live in different classes, and the When step needs what the Given step created. The wrong answer — static fields — breaks parallel execution and leaks between scenarios. Cucumber's answer is dependency injection: add one of the cucumber-picocontainer, cucumber-spring or cucumber-guice modules, and step definition classes get constructor injection with a fresh object graph per scenario.

public class ShoppingContext {          // one instance per scenario
    private final Basket basket = new Basket();
    private final PricingConfig pricing = new PricingConfig();
    private final ShippingService shipping = new ShippingService(pricing);
    private Customer customer = Customer.anonymous();
    private ShippingQuote quote;
    // accessors omitted
}

With cucumber-spring, annotating one glue class with @CucumberContextConfiguration and @SpringBootTest puts the whole application context behind the steps and makes each scenario a real end-to-end run; the trade-offs there are the same ones described in the Spring Boot testing guide. Hooks (@Before, @After, and tagged variants such as @Before("@database")) handle per-scenario setup and cleanup, and @After receives the Scenario object so you can attach a screenshot or a response body to the report when a scenario fails.

Declarative beats imperative

The single largest determinant of whether a Cucumber suite survives is the level of abstraction in the steps. Compare:

# Imperative — describes the interface, not the rule
Scenario: Discount
  Given I open "/login"
  And I type "[email protected]" into the field "#email"
  And I type "hunter2" into the field "#password"
  And I click the button "#signin"
  And I navigate to "/products/SKU-1"
  And I click "Add to basket"
  Then the element "#total" contains the text "45.00"
# Declarative — describes the rule, readable by anyone
Scenario: Members get 10% off their first order
  Given Ada is a signed-in member with no previous orders
  When she adds the 50 EUR notebook to her basket
  Then her order total is 45.00 EUR

The imperative version breaks when a designer renames a CSS class, tells the reader nothing about the business rule, and can only run through a browser. The declarative version survives redesigns, states the rule it defends, and can be bound to a service call that runs in milliseconds. Any step containing a selector, an HTTP verb, a table name or a field id is a candidate for rewriting one level up.

That said, the mapping does have to be honest. A step named "she adds the notebook to her basket" must go through the same code path the application uses, not poke a row into the database. Scenarios that fake the work they claim to perform are worse than no scenarios, because they report success for a path that was never exercised.

Living documentation

The output side is where BDD differs most from ordinary testing. Cucumber's HTML or JSON report, published by the pipeline, shows every scenario with its status; because it is generated from the same files the team agreed on, it cannot drift from the code the way a wiki page does. Feature files live in version control next to the code they describe, so a change in behaviour and a change in its documentation arrive in the same commit and the same review.

For this to be worth anything, someone outside the development team has to actually read it. If the reports are never opened, the Gherkin layer is pure overhead and the same coverage would be cheaper as plain JUnit tests — which is a legitimate outcome, and better recognised early than after two years of accumulated feature files.

Anti-patterns

UI-driven Gherkin. Covered above; it is the most common and most damaging.

Scenario explosion. Twenty scenarios enumerating combinations of two flags. Automate one illustrative example per rule and push the combinations down to a decision table at the unit level, as described in the testing fundamentals guide.

Conjunction steps. Given the customer is registered and has a valid card and lives in France hides three facts in one step and cannot be reused. Split it, or introduce a domain concept that legitimately bundles them.

Technical Then steps. Asserting on database rows, log lines or JSON paths pulls the scenario back to the developer's level and makes it unreadable by the audience it exists for.

Shared mutable state between scenarios. Scenarios must be independent and runnable in any order or in parallel. A scenario that depends on data created by the previous one will fail mysteriously the first time someone runs a tag filter.

Step definitions with logic. Loops, conditionals and calculations inside a step mean the test is computing the expected result rather than stating it. Keep the arithmetic in the feature file's example table.

Gherkin written by developers alone. Then it is a verbose JUnit test with extra indirection. Either involve the business readers or drop the layer.

Key takeaways

  • The value of BDD is concentrated in the discovery conversation; example mapping surfaces the questions that would otherwise become defects.
  • Gherkin keywords have precise jobs: Given is context, When is one event, Then is an outcome the actor can observe.
  • Scenario Outline covers a handful of illustrative cases; exhaustive boundaries belong in fast unit tests, not in feature files.
  • Share state between step definitions through constructor injection with a per-scenario context object, never through static fields.
  • Write scenarios about business rules and bind them below the user interface; imperative click-by-click Gherkin is slow, brittle and unreadable.
  • Adopt Cucumber only when non-developers read or write the scenarios — otherwise plain JUnit gives the same coverage with less machinery.

Sources and further reading

Frequently asked questions

Is BDD just TDD with different keywords?
They share the outside-in rhythm, but BDD's centre of gravity is the conversation before coding. Its practices — example mapping, specification by example, a shared vocabulary — exist to expose misunderstandings between product, development and testing while changing the requirement is still cheap. Automating the agreed examples with Cucumber is the last and least essential step; teams get most of the value from the discussion even if nothing is automated.
Do we need Cucumber, or can we write acceptance tests in plain JUnit?
Only adopt Cucumber if non-developers actually read or write the scenarios. The Gherkin layer costs an extra indirection — glue code, regular expressions, shared state — and it is a pure loss when the only readers are the developers who wrote the code. Plain JUnit tests with well-named methods and an AssertJ-based domain vocabulary give the same coverage with less machinery.
Should scenarios drive the user interface?
Usually not. Scenarios phrased as clicks and field names break whenever the layout changes and run slowly through a browser. Write scenarios about business rules and bind them to a service or HTTP API underneath the interface, then cover the interface itself with a small number of dedicated end-to-end journeys. That keeps the feature files readable and the suite fast enough to run on every commit.
How many scenarios should a feature have?
Few enough that a person will read them all. A feature that grows past roughly a dozen scenarios is usually mixing rules that deserve separate files, or is enumerating combinations that belong in a parameterised unit test. Use scenarios for the illustrative examples that settle a disagreement about the rule, and cover the exhaustive boundary cases at the unit level where they run in milliseconds.