Selenium · Browser automation foundations
How do you make Selenium tests run in parallel safely?
Short answer
Give each test its own driver instance stored in a ThreadLocal, keep test data isolated, and let the runner control parallelism. Shared drivers, shared accounts and shared files are the main sources of parallel failures.
Parallelism is a runner feature that opens several browser sessions at once. The suite must be safe for concurrent execution: each session needs its own driver, each test needs data it owns, and shared external resources need coordination.
public abstract class BaseTest {
private static final ThreadLocal<WebDriver> DRIVER = new ThreadLocal<>();
protected WebDriver driver() {
return DRIVER.get();
}
@BeforeMethod
public void setUp() {
DRIVER.set(DriverFactory.create());
}
@AfterMethod(alwaysRun = true)
public void tearDown() {
if (DRIVER.get() != null) {
DRIVER.get().quit();
DRIVER.remove();
}
}
}- TestNG can run methods or classes in parallel with a configured thread count
- JUnit 5 uses parallel execution configuration and a per-test extension
- ThreadLocal prevents two threads from sharing a browser session
- Generate unique users, orders and file names per test rather than using fixed fixtures
- Avoid tests that depend on execution order or on another test's data
- Size thread count against Grid slots, CPU and database capacity
A suite can pass serially and fail in parallel because of hidden coupling. Login with the same account in two sessions can invalidate tokens, fixed file paths collide, and a shared database row can be deleted by another test. Run the parallel suite early and often rather than enabling it at the end.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why use ThreadLocal rather than a static driver?
- 2How do you choose the thread count?
- 3What kinds of test data collide in parallel runs?
- 4How would you diagnose a test that only fails in parallel?
Say it in the interview
Each test gets its own driver stored in a ThreadLocal, and teardown quits and removes it. Test data is generated per test so accounts, orders and files do not collide. Parallelism is configured in the runner and sized against Grid slots and database capacity. I enable parallel runs early, because hidden order dependencies and shared data only show up under concurrency.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Selenium mock interview and get scored feedback on depth, clarity and confidence.