[英]How to prevent null return when initializing driver in selenium using java
I need to prevent a "null" return when I initialize my driver class.我需要在初始化驱动程序类时防止“空”返回。 Below is my code.
下面是我的代码。 Also, I need to check if the driver is null then initiate the driver if don't initiate the driver, instead keep the current initiated driver instance.
另外,我需要检查驱动程序是否为空,然后在不启动驱动程序的情况下启动驱动程序,而是保留当前启动的驱动程序实例。 Using java.
使用Java。
public class InitializeDriver {公共类 InitializeDriver {
private static WebDriver driver = null;
@BeforeTest
public static WebDriver getDriver() {
if (null == driver) {
System.setProperty("webdriver.gecko.driver", "path.to.driver");
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
return driver;
}
} }
What do you want to return if it is null?如果它为空,你想返回什么? You could wrap the null check in a
while
loop until it properly initializes.您可以将 null 检查包装在
while
循环中,直到它正确初始化。
No, you did it wrong.不,你做错了。
private static WebDriver driver = null;
driver --> class variables (static variables)驱动程序 --> 类变量(静态变量)
WebDriver driver = new FirefoxDriver();
driver --> local variable (only access on this method)驱动程序 --> 局部变量(仅在此方法上访问)
They have different scopes, so when you use driver
in other methods, you are using the first one, the static variable.它们具有不同的作用域,因此当您在其他方法中使用
driver
时,您使用的是第一个,即静态变量。
How to fix:怎么修:
private static WebDriver driver; //default is null
@BeforeTest
public static WebDriver getDriver() {
// check null if you want to lazy creation, if not, just remove if()
if (null == driver) {
System.setProperty("webdriver.gecko.driver", "path.to.driver");
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
return driver;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.