1

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?

Mellissa
  • 138
  • 5
  • So don’t change it. As it is, every thread will get its own driver. Isn’t that what you want? – Bohemian Sep 22 '20 at 18:45
  • the problem is, it spawns the number of browsers, but theyre all sharing the same browser instance. So its attempting to execute three different sets of test code within a shared instance and all the tests are overwriting each other, causing the tests to fail. – Mellissa Sep 22 '20 at 18:53

1 Answers1

1

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;
    }
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722