πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
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 + Java
import 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;
    }
}