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

Execution order

For a scenario inside a Rule, JUnit 5 runs:

  1. Feature @BeforeEachfeatureBackground() (e.g. signed-in shopper, empty cart)
  2. Rule @BeforeEachruleBackground() (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 featureBackground(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 scenario_1() { /* ... */ }
}

@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 scenario_1() { /* ... */ }
}
}

Run it

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