← Back to libraryQuestion 276 of 468
🔬TestNG & JUnitAdvanced

Parallel Execution

📌 Definition:

Both frameworks can run tests concurrently to cut suite time. TestNG configures parallelism in testng.xml (parallel + thread-count); JUnit 5 uses junit.jupiter.execution.parallel properties. Thread safety is required either way.

📖 Detailed Explanation:

TestNG: <suite parallel='methods|classes|tests|instances' thread-count='4'> runs those units concurrently; @DataProvider(parallel=true) parallelizes data rows. JUnit 5: enable junit.jupiter.execution.parallel.enabled=true with a config strategy and @Execution(CONCURRENT). The hard requirement in both is THREAD SAFETY: shared mutable state (a static WebDriver, shared test data) collides across threads. Use ThreadLocal<WebDriver>, avoid statics, and isolate data per thread. Parallelism turns hour-long suites into minutes but exposes hidden shared-state bugs — a frequent interview and real-world pitfall.

🔑 Key Points:
  • TestNG: parallel + thread-count in XML; JUnit5: parallel properties + @Execution
  • Parallelize methods/classes/tests (or DataProvider rows)
  • Thread safety required: ThreadLocal driver, no static state
  • Isolate test data per thread to avoid collisions
🌍 Real-World Example:

Setting parallel='methods' thread-count='5' cuts a Selenium suite from 50 to ~12 minutes after refactoring a shared static driver into a ThreadLocal so each thread drives its own browser.

🎯 Scenario-Based Interview Question:

You enable parallel execution and tests fail randomly with wrong-page/stale-element errors. Root cause and fix?