How to use thread local in selenium webdriver automation

Thread Local usage in Selenium Web Driver Automation

Lets understand what is the benefit of using ThreadLocal. When you have an object which is not thread-safe, then we can make use of ThreadLocal, which makes the instance thread safe. In case of test automation, one may wants to run tests parallel. So in case of Selenium web driver automation, I want to make the driver instance as thread safe using ThreadLocal.
Its very simple to add the basic ThreadLocal to your driver instance. Let's see how to do.

How to use Thread Local in Selenium Automation

  • Create a class for handling ThreadLocal instance
  • Set the driver instance to WebDriverPool
  • Access the driver instance from WebDriverPool

Step1 :- Create a class 'WebDriverPool.java'
Which has simple get and set methods to set and access the driver instances
public class WebDriverPool {

    private static ThreadLocal browser = new ThreadLocal();

    public static WebDriver getWebDriver() {
        return browser.get();
    }

    static void setWebDriver(WebDriver driver) {
        browser.set(driver);
    }
}
Step2 :- Set the driver instance to WebDriverPool
public class DriverSetup {

    public void setupDriver() {
        WebDriver driver = new FirefoxDriver()
        WebDriverPool.setWebDriver(driver);
    }
    
}
Step3 :- Get the driver instance from WebDriverPool in your PageClass
public class PageClass {

    public static WebDriver getBrowser() {
        WebDriverPool.getWebDriver();
    }
    
}

**I have written sample codes, just focus on highlighted lines of code to understand the usage**
Hope you get some idea on how to use ThreadLocal. Please let me know in comments if you have anything to say. Happy learning.

Comments

Post a Comment