Testing / Cucumber Interview Questions
How do you implement dependency injection across step definition classes using PicoContainer or Spring?
PicoContainer, Cucumber-JVM's zero-configuration default DI option, automatically detects step definition classes with a single constructor and wires up shared instances of any classes referenced across multiple step definition classes, with no explicit registration required.
public class SharedContext { private String lastResponseBody; // getters/setters } public class ApiSteps { private final SharedContext context; public ApiSteps(SharedContext context) { this.context = context; } @When("a request is sent") public void a_request_is_sent() { context.setLastResponseBody(apiClient.get("/status").body()); } } public class VerificationSteps { private final SharedContext context; public VerificationSteps(SharedContext context) { this.context = context; } @Then("the response should not be empty") public void the_response_should_not_be_empty() { assertFalse(context.getLastResponseBody().isEmpty()); } }
For projects already using Spring, the Spring DI module lets step definition classes be Spring beans instead, gaining access to Spring's configuration, profiles, and existing application context, which is often preferred when a test suite needs to reuse production Spring beans (like a configured HTTP client or a test-specific database connection bean) rather than duplicating that setup separately for tests.
More Related questions...