Testing / Cucumber Interview Questions
What is Dependency Injection used for in Cucumber?
Cucumber creates a fresh instance of every step definition class for each scenario, which means step definition methods spread across multiple classes (for readability and organization) can't simply share state through instance fields the way methods within a single class normally could. Dependency Injection solves this by having a DI container manage shared instances that get injected into every step definition class needing them.
public class SharedContext { private LoginResult loginResult; // getters and setters } public class LoginSteps { private final SharedContext context; public LoginSteps(SharedContext context) { this.context = context; } @When("{string} logs in with password {string}") public void logs_in(String username, String password) { context.setLoginResult(loginService.login(username, password)); } }
Cucumber-JVM supports several DI options, PicoContainer (the built-in default, requiring no extra configuration), Spring, and Guice among them, letting a shared context object like the one above be injected consistently into every step definition class that needs access to state produced earlier in the same scenario.
More Related questions...