javamultithreadingseleniumselenium-webdriverparallel-testing

How to create an instance of a static class so it can be called from a separate class?


apologies as this is a really basic problem, but Im really struggling with the basics of this concept.

I have created a public static class to set a browser

private static ThreadLocal<WebDriver> driver = new ThreadLocal<>();

public static void setDriver(@NonNull String browserName) {
    if (browserName.equalsIgnoreCase("chrome")) {
       WebDriverManager.chromedriver().setup();
       driver.set(new ChromeDriver());
    } else if (browserName.equalsIgnoreCase("firefox")) {
       WebDriverManager.firefoxdriver().setup();
       driver.set(new FirefoxDriver());
    }
}

below this, I get the browser using

public static driver getDriver() {
    return driver.get();
}

This works fine when generating a single instance, but I need to run this in parallel using multiple instances of the browser.

The problem is, I cant just change public static driver getDriver() to public driver getDriver() because it breaks everything else down the line. So I need to instantiate an instance of this class. Unfortunately, everything I have tried completely fails one way or another.

How can I instantiate this class to use in other classes throughout my project?


Solution

  • You need to override the initialValue() method. Something like:

    private static ThreadLocal<WebDriver> driver = new ThreadLocal<>() {
        @Override protected WebDriver initialValue() {
             return getDriver("chrome");
         }
    };
    
    private static WebDriver getDriver(@NonNull String browserName) {
        if (browserName.equalsIgnoreCase("chrome")) {
            WebDriverManager.chromedriver().setup();
            return new ChromeDriver();
        } else if (browserName.equalsIgnoreCase("firefox")) {
            WebDriverManager.firefoxdriver().setup();
            return new FirefoxDriver();
        } else {
            return null;
        }
    }