I have used the accepted solution here and came up with the following code:
Referenced Libraries:
Feature:
Feature: FeatureA
Scenario: ScenarioA
Given
When
Then
Scenario: ScenarioB
Given
When
Then
BaseStep:
public class BaseStep {
protected WebDriver driver = null;
private static boolean isInitialized = false;
@Before
public void setUp() throws Exception {
if (!isInitialized) {
driver = SeleniumUtil.getWebDriver(ConfigUtil.readKey("browser"));
isInitialized = true;
}
}
@After
public void tearDown() {
driver.quit();
}
}
StepA:
public class StepA {
private BaseStep baseStep = null;
private WebDriver driver = null;
// PicoContainer injects BaseStep class
public StepA(BaseStep baseStep) {
this.baseStep = baseStep;
}
@Given("^I am at the Login page$")
public void givenIAmAtTheLoginPage() throws Exception {
driver = baseStep.driver;
driver.get(ConfigUtil.readKey("base_url"));
}
@When
@When
@Then
@Then
}
However, the driver "dies" after tearDown()
of ScenarioA and becomes null on Given step of ScenarioB (both scenarios use the same Given). I am not using Maven.
It's because of this line:
private static boolean isInitialized = false;
For each scenario, cucumber creates a new instance for every step file involved. Hence, the driver
in BaseStep
is always null when a scenario starts.
The static isInitialized
boolean is not part of an instance, it's bound to the class it lives in and it's alive until the JVM shuts down. The first scenario sets it to true
, meaning that when the second scenario starts it's still true
and it does not reinitialize the driver in the setUp()
method.
You probably want to make driver
static to share the same instance with both scenarios.