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→@BeforeEachon the outer test class - Rule-level
Background→@BeforeEachon the@Nestedrule class - Background title →
@DisplayNameon the@BeforeEachmethod - Background description → JavaDoc on the
@BeforeEachmethod - Both feature- and rule-level backgrounds run before each scenario inside a
Rule
Execution order
For a scenario inside a Rule, JUnit 5 runs:
- Feature
@BeforeEach—featureBackground()(e.g. signed-in shopper, empty cart) - Rule
@BeforeEach—ruleBackground()(rule-specific setup) - 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