Skip to main content

Implementing Steps

A fully working example — step methods are implemented in the marker class with real assertions, and tests run green.

Source: examples/getting-started/example-3 on GitHub.

What this demonstrates

  • The end-to-end workflow from spec file to passing tests
  • Step methods implemented directly on the marker class
  • The generator detects inherited methods and stops generating step stubs / abstract declarations for them
  • State management via plain instance fields — no DI framework needed
  • Real JUnit assertions in step methods

The workflow

  1. Create a marker class annotated with @Gherkin2JUnit("…").
  2. Compile — the generator emits an abstract class with one abstract method per step.
  3. Implement the step methods on the marker class.
  4. Recompile — the generator now sees inherited methods and omits the corresponding abstract declarations.
  5. The generated test class can now be instantiated — JUnit runs it.

This example uses concrete mode (@Gherkin2JUnitOptions(shouldBeAbstract = false)) so the generated class is itself runnable. For the abstract-mode equivalent (the default), see Abstract Mode.

State management

State is shared between steps via instance fields on the marker class:

private final List<CartItem> cart = new ArrayList<>();

public void iHaveAnEmptyShoppingCart() {
cart.clear();
}

public void iAdd$p1WithQuantity$p2AndUnitPrice$p3(String name, Integer quantity, Double unitPrice) {
cart.add(new CartItem(name, quantity, unitPrice));
}

public void theCartSubtotalShouldBe$p1(Double expectedSubtotal) {
double subtotal = cart.stream()
.mapToDouble(item -> item.quantity() * item.unitPrice())
.sum();
assertEquals(expectedSubtotal, subtotal, 0.001);
}

Parameter names in your implementation can be anything — only the method name and parameter types need to match the generated signature.

Run it

cd examples/getting-started/example-3
mvn test