Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 37 ยท Step Definitions

Sharing State Between Steps and Step Classes

Share state between Cucumber steps safely: instance fields, a scenario-scoped world object, PicoContainer and Spring injection, and why static fields cause flaky tests.

A scenario is a story told in steps, and each step builds on what the previous one left behind: a Given creates an account, a When changes it, a Then inspects it. In Cucumber, steps have no parameters or return values that connect them, so state must live somewhere. Where you put it determines whether your suite is clean and isolated or flaky and tangled.

Option 1: fields in one step class

The simplest approach, and the right one for small features, is instance fields in a single step class:

Java
public class AccountSteps {
    private Account account;                  // created per scenario

    @Given("an account with {int} dollars")
    public void anAccountWith(int balance) { account = new Account(balance); }

    @When("the holder withdraws {int} dollars")
    public void withdraws(int amount) { account.withdraw(amount); }

    @Then("the balance is {int} dollars")
    public void balanceIs(int expected) { assertEquals(expected, account.balance()); }
}

Cucumber creates a new instance of the class for every scenario, so account starts as null each time. No cleanup is needed.

The limit appears when sentences about the same scenario live in different classes: AccountSteps creates the account, NotificationSteps needs to check that an email was sent to the account holder. They need to share data. There are three ways, in increasing order of recommendation.

Option 2: static fields (do not)

A static field is shared by all scenarios in the run, so values leak from one scenario into the next:

Java
public class AccountSteps {
    static Account account;     // dangerous: survives between scenarios
}

Consequences: scenarios pass or fail depending on the order they run, parallel execution corrupts values, and bugs appear on CI but not locally. The stand-in below demonstrates the leak. Scenario two never creates an account, yet it passes by accident because scenario one left one behind. Change the first scenario's balance and watch the second one fail without having changed at all.

Java Stand-in: a static field leaks between scenarios

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The same hidden dependency shows up as flaky tests when scenarios are filtered by tag or run in parallel. Avoid static state in glue code.

Option 3: a world object per scenario

Put the shared state in a plain class (often called the world, context or scenario state), and give every step class a reference to the same instance for the length of one scenario:

Java
public class ShopWorld {
    public Account account;
    public Receipt lastReceipt;
    public final List<String> sentEmails = new ArrayList<>();
}
Java
public class AccountSteps {
    private final ShopWorld world;

    public AccountSteps(ShopWorld world) {      // constructor injection
        this.world = world;
    }

    @Given("an account with {int} dollars")
    public void anAccountWith(int balance) { world.account = new Account(balance); }
}

public class NotificationSteps {
    private final ShopWorld world;

    public NotificationSteps(ShopWorld world) {
        this.world = world;
    }

    @Then("an email is sent to the holder")
    public void anEmailIsSent() {
        assertTrue(world.sentEmails.contains(world.account.email()));
    }
}

Who creates the ShopWorld and passes it to both constructors? A dependency injection (DI) container, and Cucumber integrates with several:

Module Dependency Notes
cucumber-picocontainer PicoContainer Smallest option: add the jar and it works with constructor injection
cucumber-spring Spring Use when the app under test is a Spring application; scenario scope via @ScenarioScope or cucumber-glue scope
cucumber-guice Google Guice Similar, with Guice modules
cucumber-jakarta-cdi, cucumber-openejb CDI / OpenEJB For Jakarta EE style projects

With PicoContainer you only add the dependency; no configuration is required. Every class in the glue package that appears in a step class's constructor is created once per scenario and shared among all classes that ask for it. When the scenario ends, the container is discarded and so is the state.

A container you can run

This stand-in reproduces what PicoContainer does with the constructors: it looks at a class's constructor parameters, creates each needed type once per scenario, and hands the same instance to everyone. At the end of the scenario the container is dropped. Two scenarios produce two independent worlds.

Java Stand-in: constructor injection, one world per scenario

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The second scenario expects two emails and gets exactly two, because the first scenario's email was discarded with its container. With a static list, it would have found three.

What belongs in the world

Keep the world small and plain:

  • Yes: the entities created by Given steps, the last result or error of the When step, collected observations the Then steps compare.
  • Maybe: handles to the system under test (an HTTP client, a WebDriver), but better provided as separate injectable classes.
  • No: logic. A world with methods that do business work turns into a second implementation of the application.

A common pattern for failure scenarios is to store the exception from the When step in the world so a Then step can assert on it:

Java
@When("the holder withdraws {int} dollars")
public void withdraws(int amount) {
    try {
        world.account.withdraw(amount);
    } catch (InsufficientFundsException e) {
        world.lastError = e;
    }
}

@Then("the withdrawal is refused")
public void refused() {
    assertNotNull(world.lastError);
}

Resources and cleanup

Objects created by the container live for one scenario. If a world holds something that must be closed (a browser, a database connection), implement cleanup in an @After hook, covered in the chapter on hooks. For expensive shared resources (a started server), create them once per run, not per scenario, using a suitable DI scope or a lazily initialized singleton that is read-only from the scenarios' point of view.

Checklist

  1. No static mutable fields in glue code.
  2. One small world class per scenario, injected by constructor.
  3. Split step classes by concept; share only through the world.
  4. Store results (and errors) of When steps in the world, assert in Then steps.
  5. Choose PicoContainer unless you need Spring's beans for the application under test.

Chapter 4 moves from single examples to parameterized ones: Scenario Outline.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does an instance field in a step class not leak between scenarios?

    A new glue object per scenario keeps instance state isolated.
  2. 2. What is wrong with a static field holding scenario state?

    Static state survives across scenarios, hiding missing setup and breaking parallel execution.
  3. 3. How do two step classes share the same world object?

    The container creates the world once per scenario and injects the same instance wherever it is requested.
  4. 4. Which is the lightest DI module for Cucumber-JVM?

    PicoContainer needs only the dependency and constructor injection, with no configuration.
  5. 5. What is a good use of the world object?

    The world is plain shared state, not a second implementation of the application.

Summary

  • Steps share state through fields; Cucumber creates fresh glue objects per scenario.
  • Never use static mutable state: it leaks between scenarios and breaks parallel runs.
  • For several step classes, inject a small world object through constructors (PicoContainer or Spring).
  • Store results and errors of When steps in the world, and assert on them in Then steps.
  • Clean up resources in hooks; share expensive resources read-only at run scope.

Next: Scenario Outlines