使用PicoContainer,共享WebDriver在第二种情况下变为null [英] Shared WebDriver becomes null on second scenario using PicoContainer
问题描述
我使用了
功能:
功能:FeatureA
场景:ScenarioA
给定
当
然后
场景:场景B
给定
当
然后
BaseStep:
public class BaseStep {
protected WebDriver driver = null;
private static boolean isInitialized = false;
@Before
public void setUp()抛出异常{
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注入BaseStep类
public StepA(BaseStep baseStep){
this.baseStep = baseStep;
}
@Given(^我在登录页面$)
public void givenIAmAtTheLoginPage()抛出异常{
driver = baseStep.driver;
driver.get(ConfigUtil.readKey(base_url));
}
@When
@When
@Then
@Then
}
然而,驱动程序在ScenarioA的 tearDown()
之后死亡并变为null在ScenarioB的给定步骤(两个场景使用相同的给定)。我没有使用Maven。
这是因为这一行:
private static boolean isInitialized = false;
对于每个场景,cucumber为每个涉及的步骤文件创建一个新实例。因此,当场景开始时, BaseStep
中的驱动程序
始终为空。
静态 isInitialized
boolean不是实例的一部分,它绑定到它所在的类,并且它一直存在,直到JVM关闭。第一个场景将其设置为 true
,这意味着当第二个场景启动时它仍然是 true
并且它不会重新初始化 setUp()
方法中的驱动程序。
您可能想要驱动程序
static与两种情况共享同一个实例。
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.
这篇关于使用PicoContainer,共享WebDriver在第二种情况下变为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!