Skip to main content

Background

Gherkin Background blocks set up shared state for every scenario in their scope. They map to JUnit @BeforeEach methods.

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

What this demonstrates​

  • Feature-level Background → @BeforeEach on the outer test class
  • Rule-level Background → @BeforeEach on the @Nested rule class
  • Background title → @DisplayName on the @BeforeEach method
  • Background description → JavaDoc on the @BeforeEach method
  • Both feature- and rule-level backgrounds run before each scenario inside a Rule
  • Background steps are ordinary step methods, implemented in the concrete subclass alongside the scenario steps — the generated @BeforeEach methods simply call them

Execution order​

For a scenario inside a Rule, JUnit 5 runs:

  1. Feature @BeforeEach — background() (e.g. signed-in shopper, empty cart)
  2. Rule @BeforeEach — ruleBackground() (rule-specific setup)
  3. Scenario @Test — the test itself

Scenarios at the top level (outside any Rule) run only the feature-level background.

Generated structure​

public abstract class ShoppingCartScenarios extends ShoppingCartFeature {

@BeforeEach
@DisplayName("Background: Start with a signed-in shopper")
public void background(TestInfo testInfo) {
iAmSignedInAs$p1("alice@example.com");
iHaveAnEmptyShoppingCart();
}

@Test
@DisplayName("Scenario: View empty cart message")
public void scenario_1() { /* ... */ }

@Nested
@DisplayName("Rule: Free shipping applies to orders over 50 euros")
public class Rule_1 {
@BeforeEach
@DisplayName("Background: Cart near the shipping threshold")
public void ruleBackground(TestInfo testInfo) {
myCartSubtotalIs$p1(45.00);
}

@Test
public void rule_1_scenario_1() { /* ... */ }

@Test
public void rule_1_scenario_2() { /* ... */ }
}

@Nested
@DisplayName("Rule: Loyalty points are earned on every purchase")
public class Rule_2 {
@BeforeEach
public void ruleBackground(TestInfo testInfo) {
iHave$p1LoyaltyPoints(100);
}

@Test
public void rule_2_scenario_1() { /* ... */ }
}
}

The test class​

Background steps need no special treatment — ShoppingCartTest implements them like any other step, and by the time a rule-level background or a scenario runs, the feature-level background has already signed the shopper in:

ShoppingCartTest.java
public class ShoppingCartTest extends ShoppingCartScenarios {

private String signedInShopper;
private int loyaltyPoints;

@Override
public void iAmSignedInAs$p1(String email) {
signedInShopper = email;
}

@Override
public void iHave$p1LoyaltyPoints(Integer points) {
loyaltyPoints = points;
}

@Override
public void iPurchaseItemsTotalling$p1(Double total) {
assertNotNull(signedInShopper, "Only a signed-in shopper can purchase");
loyaltyPoints += (int) (total * POINTS_PER_EURO);
}

// ... the remaining steps
}

Run it​

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