简体   繁体   中英

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.

public class 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.

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM