Back to Challenges
Tests Interfere When Run in Parallel
advanced Java 20 minA suite passes serially and fails chaotically with parallel threads. Find the shared state and isolate each test's driver.
The Scenario
To speed up the suite, someone set parallel="methods" with four threads in testng.xml. Now tests fail with NoSuchSessionException, browsers close mid-test, and one test’s assertions see another test’s page. Setting the thread count back to one makes everything pass.
Your Task
Identify the shared state and restructure driver management so every test thread owns its own browser, with no leaks between tests.
What Good Looks Like
- No static
WebDriverfield. - A
ThreadLocal(or equivalent) behind a small manager class. quit()andremove()both happen in teardown.- Test code changes minimally; page objects receive the driver by constructor.
Your task
A suite passes serially and fails chaotically with parallel threads. Find the shared state and isolate each test's driver.
Problem Code
public class BaseTest {
protected static WebDriver driver;
@BeforeMethod
public void start() {
driver = new ChromeDriver();
}
@AfterMethod
public void stop() {
driver.quit();
}
}
// testng.xml: <suite name="e2e" parallel="methods" thread-count="4">
public class CheckoutTest extends BaseTest {
@Test public void appliesCoupon() { driver.get("https://app.example.com/checkout"); /* ... */ }
@Test public void placesOrder() { driver.get("https://app.example.com/checkout"); /* ... */ }
}
Need Help?
Solution
Try to solve the challenge yourself before revealing the solution.
Lessons that cover this
- Driver Factory and Thread Safety Build a WebDriver factory that reads configuration, supports local, Grid and cloud targets, and hands each parallel test its own driver via ThreadLocal or fixtures without leaks.
- Parallel Execution Run Selenium tests in parallel to dramatically reduce test execution time.