Skip to main content


Using Selenium with Java and TestNG (1)

Parallel Test Execution & Multi-thread

In this blog, I‘ll introduce how we use Selenium and TestNG to execute the test cases in parallel. If you’re using selenium and testNG, it would help reduce the test execution time.

As we know, testNG has the feature of parallel test execution. We could run testNG test cases on parallel by adding some property in the testng.xml.

For example:

<suite name=”My suite” parallel=”methods” thread-count=”5″>

<suite name=”My suite” parallel=”tests” thread-count=”5″>

<suite name=”My suite” parallel=”classes” thread-count=”5″>Using Selenium with Java and TestNG

<suite name=”My suite” parallel=”instances” thread-count=”5″>

Here we can set the parallel at the level of methods, tests, classes and instances. And We can set how many threads we want to use in the test execution. But there is a problem that Selenium WebDriver is NOT thread safe. WebDriver will not respond if we just use the testNG’s parallel feature. What we need to do is to introduce a thread local variable:

public static ThreadLocal<WebDriver> ThreadDriver=new ThreadLocal<WebDriver>() ;

I put this Thread Local WebDriver in my Driver Manager which is a class has the getter of WebDriver instance. Here is the code of the getter method:

public static WebDriver getDriver(){WebDriver driver= DriverManager.ThreadDriver.get();if (driver==null){ if (browserType.equals(“firefox”)){driver = new FirefoxDriver() ThreadDriver.set(driver); } } return driver; } 

In the getter, when we want to get the current WebDriver Instance, it will firstly check “if the WebDriver instance is already created on the current thread”. If yes, then, the getter will return the current instance, if not, the getter will create a new instance and bind it to the current thread.

By this way, our WebDriver is thread-safe now. And we could use testNG to execute test cases in parallel. And this is the precondition of using selenium grid which could distribute the test cases execution into multiple computers.

The full code of my small test framework build with selenium is here:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Colin Zhang

More from this Author

Follow Us