πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 91 of 100
BDD / Cucumber
Intermediate

Sharing Step Definition Classes Safely Across Features

πŸ”—Scenario Overview

Sharing Step Definition Classes Safely Across Features

Key Takeaways & Cheat Sheet

  • βœ“Use Cucumber dependency injection frameworks (PicoContainer or Spring)
  • βœ“Share active test contexts dynamically without using fragile static fields
  • βœ“Define generic hooks (like screenshots on failure) in a centralized base step class
  • βœ“Bypass manual driver instantiation within sub-definition classes

Short Direct Answer

To share state (like user IDs or session tokens) across step definitions safely, use Dependency Injection (such as Cucumber-PicoContainer). Create a shared "Test Context" container class and inject it into the constructors of your step definition classes, avoiding static state conflicts in parallel runs.

⚠️ Senior Warning (Red Flag)

Never use global static variables to share states (like a user email generated in one step) across step definitions. Static sharing causes state conflicts and race conditions in parallel runs.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

PicoContainer manages the lifecycle of these context objects, creating a fresh, isolated container for each scenario execution to guarantee thread safety.

SeleniumAutomation.java
Selenium 4 + Java
// Shared Context container
public class TestContext {
    public String createdUserEmail;
    public WebDriver driver = DriverManager.getDriver();
}

// Step Definition Class A
public class AccountSteps {
    private TestContext context;
    public AccountSteps(TestContext context) { this.context = context; }

    @Given("I register a new user")
    public void registerUser() {
        context.createdUserEmail = "test_" + System.currentTimeMillis() + "@email.com";
        // registration logic...
    }
}

// Step Definition Class B
public class OrderSteps {
    private TestContext context;
    public OrderSteps(TestContext context) { this.context = context; }

    @Then("I verify order matches the created account email")
    public void verifyOrder() {
        System.out.println("Verifying order for: " + context.createdUserEmail);
    }
}