← Back to libraryQuestion 260 of 468
🥒Cucumber / BDDAdvanced

Sharing State Between Steps (Dependency Injection)

📌 Definition:

Steps for one scenario often live in different step-definition classes but need to share data (a logged-in user, a created order id). Cucumber uses dependency injection (PicoContainer, Spring, Guice) to share a context object across step classes per scenario.

📖 Detailed Explanation:

Using instance fields to pass data works only within a single class; across classes you need shared state. The idiomatic solution is a DI module (cucumber-picocontainer is the simplest): create a plain 'World'/context class, inject it into the constructors of each step-definition class, and Cucumber gives all classes the SAME instance for a scenario (fresh per scenario, ensuring isolation). Alternatives are Spring (cucumber-spring) or Guice. Avoid static/global state to share data — it leaks between scenarios and breaks parallel runs. Proper DI keeps steps decoupled yet able to collaborate.

🔑 Key Points:
  • Steps across classes share data via DI (PicoContainer/Spring/Guice)
  • Inject a shared context/World object into step-class constructors
  • Same instance per scenario, fresh each scenario (isolation)
  • Avoid static/global state — it leaks and breaks parallelism
🌍 Real-World Example:

A TestContext holding the created order id is injected into both OrderSteps and PaymentSteps via PicoContainer, so the payment step reads the id the order step stored — without static variables.

🎯 Scenario-Based Interview Question:

Login steps and checkout steps are in different classes, and checkout needs the logged-in user. How do you share it correctly?