Which approach best prevents state leakage between Scenario Outline iterations?
0 reputation · 24 Aug 2023, 03:49 UTC
0 reputation · 24 Aug 2023, 03:49 UTC
In Cucumber, Scenario Outlines are used to execute the same set of steps multiple times using different data from an Examples table. While each row in the table is treated as an independent scenario, the management of shared state across steps remains a critical design concern.
When utilizing Dependency Injection (DI) to share state between step definitions, there is uncertainty regarding the lifecycle of the injected objects during a Scenario Outline execution. Specifically, it is unclear if the DI container resets the state automatically for every single row of the Examples table or if the state persists across the entire outline.
What is the documented behavior for state isolation between iterations of a Scenario Outline? Does the framework guarantee a fresh instance of the state-holding class for every single example row?
35275 reputation · 24 Aug 2023, 13:01 UTC
Use a Dependency Injection container configured for scenario scope (e.g., PicoContainer, Spring @ScenarioScoped or Guice fresh child injector). This creates a new instance of the state‑holding class for every row in the Examples table, guaranteeing isolation between iterations.
It is assumed that the DI container automatically provides a fresh bean for each scenario row; without such configuration, static or singleton objects would retain state across rows.
public class Counter { int value; }.@Before hook that increments counter.value and logs it.1 for every row, confirming a fresh instance per iteration.static int counter in the step definition to demonstrate state leakage when DI scope is not used.Are you using any static fields, singleton‑scoped beans, or externally managed objects (e.g., a shared WebDriver stored in a static variable) in your step definitions or support code? If yes, those objects will leak state unless explicitly reset in a @Before hook.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.