Back to All Scenarios
Scenario 53 of 100
Framework Design
Advanced
Creating a Dynamic Multi-Browser Driver Factory
ποΈScenario Overview
Creating a Dynamic Multi-Browser Driver Factory
Key Takeaways & Cheat Sheet
- βLeverage Factory Pattern to centralize driver creation architecture
- βAccept parameter parameters to dictate target browser choices
- βIsolate and build specific BrowserOptions instances cleanly
- βSupport standardized configurations like headless, window-sizes, and sandboxing
Short Direct Answer
To support cross-browser testing, implement a clean Driver Factory pattern. Centralize your setup logic inside a single class that takes a browser parameter (e.g., Chrome, Firefox, Edge, Safari), configures their respective browser options (like headless execution and standard viewports), and returns the configured driver instance.
β οΈ Senior Warning (Red Flag)
Never instantiate drivers directly in your test classes. Hardcoding ChromeDriver inside tests makes it impossible to run cross-browser execution, locking your framework to a single environment.
π‘ STAR Deep Dive Explanation & Pro Tip
Using System.getProperty allows you to pass both the browser type and headless flags dynamically from command-line executions (e.g., Maven, Gradle, or Jenkins build steps).
SeleniumAutomation.java
Selenium 4 + Javaimport org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.edge.EdgeDriver;
public class DriverFactory {
public static WebDriver createInstance(String browser) {
WebDriver driver;
switch (browser.toLowerCase().trim()) {
case "chrome":
ChromeOptions chromeOpts = new ChromeOptions();
chromeOpts.addArguments("--window-size=1920,1080");
if (System.getProperty("headless") != null) chromeOpts.addArguments("--headless=new");
driver = new ChromeDriver(chromeOpts);
break;
case "firefox":
FirefoxOptions ffOpts = new FirefoxOptions();
if (System.getProperty("headless") != null) ffOpts.addArguments("-headless");
driver = new FirefoxDriver(ffOpts);
break;
default:
throw new IllegalArgumentException("Unsupported browser: " + browser);
}
return driver;
}
}