Back to All Scenarios
Scenario 61 of 100
Framework Design
Advanced
Enabling Parallel Execution (TestNG & JUnit)
β‘Scenario Overview
Enabling Parallel Execution (TestNG & JUnit)
Key Takeaways & Cheat Sheet
- βEnforce ThreadLocal storage wrappers on all WebDriver instances
- βConfigure dynamic multi-thread allocations inside testng.xml settings
- βAvoid sharing mutable static class variables across test files
- βUtilize isolated data profiles to prevent database conflicts
Short Direct Answer
To run tests in parallel, ensure thread isolation by wrapping your WebDriver instance in a `ThreadLocal` object. This assigns an independent, isolated browser session to each execution thread. Configure thread counts and parallelization modes (methods, classes, or suites) inside your `testng.xml` configuration file.
β οΈ Senior Warning (Red Flag)
Never share a single static WebDriver instance across parallel execution threads. Thread conflict will cause tests to hijack each other's sessions, resulting in immediate crashes and browser freeze states.
π‘ STAR Deep Dive Explanation & Pro Tip
Always call threadDriver.remove() in your teardown methods. If omitted, threads reused by the TestNG thread pool will retain references to closed driver sessions, causing memory leaks and test failures.
SeleniumAutomation.java
Selenium 4 + Javaimport org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ThreadLocalDriver {
// ThreadLocal container guarantees driver isolation per thread
private static ThreadLocal<WebDriver> threadDriver = new ThreadLocal<>();
public static void setDriver(WebDriver driver) {
threadDriver.set(driver);
}
public static WebDriver getDriver() {
return threadDriver.get();
}
public static void removeDriver() {
if (threadDriver.get() != null) {
threadDriver.get().quit();
threadDriver.remove(); // Clean thread memory
}
}
}
// Usage in BaseTest:
// ThreadLocalDriver.setDriver(new ChromeDriver());
// WebDriver driver = ThreadLocalDriver.getDriver();