← Back to libraryQuestion 291 of 468
🏗️Framework DesignAdvanced

WebDriver Management (Factory + ThreadLocal)

📌 Definition:

A framework should centralize WebDriver creation/teardown in a factory and, for parallel execution, store the driver in a ThreadLocal so each thread has its own isolated instance. Tests never instantiate the driver directly.

📖 Detailed Explanation:

A DriverFactory/DriverManager reads config (browser, headless, grid URL), creates the right WebDriver (Selenium Manager or options), and hands it out; a corresponding teardown quits it. For parallel runs, a static ThreadLocal<WebDriver> gives each thread a separate driver, preventing cross-thread interference (the #1 parallel bug). Tests/pages obtain the driver via DriverManager.getDriver() rather than a shared field. This centralization enables cross-browser switching by config, clean lifecycle management via hooks/@Before-@After, and safe parallelism. Leaking drivers (not quitting) or sharing one across threads are classic framework defects.

🔑 Key Points:
  • Centralize driver create/quit in a DriverFactory (config-driven)
  • ThreadLocal<WebDriver> gives each thread its own driver (parallel-safe)
  • Tests/pages get the driver via DriverManager.getDriver()
  • Never share one driver across threads; always quit to avoid leaks
🌍 Real-World Example:

DriverFactory.createDriver() reads browser=chrome from config and stores it in ThreadLocal; five parallel threads each get their own Chrome, and @AfterMethod calls driver.quit() and removes the ThreadLocal to prevent leaks.

🎯 Scenario-Based Interview Question:

Your framework works serially but fails randomly when parallelized, with actions hitting the wrong browser. What's the design flaw and fix?