Shared WebDriver becomes null on second scenario using PicoContainer

旧巷老猫 提交于 2019-12-03 10:11:07

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.

From Luciano's answer, this is what I ended up with:

Features:

Feature: FeatureA

  Scenario: ScenarioA
    Given I am at the Login page
    When 
    Then

  Scenario: ScenarioB
    Given I am at the Login page
    When 
    Then


Feature: FeatureB

  Scenario: ScenarioC
    Given I am at the Login page
    When 
    Then

BaseStep:

public class BaseStep {
    protected WebDriver driver = null;

    @Before
    public void setUp() throws Exception {
        driver = SeleniumUtil.getWebDriver(ConfigUtil.readKey("browser"));
    }

    @After
    public void tearDown() {
        driver.quit();
    }

}

Steps:

public class FeatureAStep {
    private WebDriver driver = null;

    // PicoContainer injects BaseStep class
    public FeatureAStep(BaseStep baseStep) {
        this.driver = baseStep.driver;
    }

    @Given("^I am at the Login page$")
    public void givenIAmAtTheLoginPage() throws Exception {
        driver.get(ConfigUtil.readKey("base_url"));
    }

  @When
  @When
  @Then
  @Then
}


public class FeatureBStep {
    private WebDriver driver = null;

    // PicoContainer injects BaseStep class
    public FeatureBStep(BaseStep baseStep) {
        this.driver = baseStep.driver;
    }

  @When
  @Then
}

I have 2 Feature files and 2 Step Definition classes. ScenarioC shares the same Given from Scenarios A and B that is defined in FeatureAStep. When and Then of ScenarioC is defined in FeatureBStep. I did not make the WebDriver static in BaseStep using PicoContainer. Both Feature files executed successfully.


Related Reading:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!