Factory Design Pattern in Selenium

  

What is the Factory Design Pattern?

The Factory Design Pattern is a creational design pattern used to create objects without exposing the instantiation logic to the client.

In Selenium, it's commonly used to:

  • Initialize different browsers (Chrome, Firefox, Edge, etc.)

  • Return the correct WebDriver object based on input


Why Use Factory Pattern in Selenium?

AdvantageDescription
Centralized object creationAll drivers created in one place
ScalableEasily add support for new browsers
Clean codeAvoids if-else or switch clutter in tests
Promotes abstractionClients don’t know the exact class being used


Example: Factory Pattern for Browser Initialization

Project Structure

FactoryDesignPatternSelenium/ ├── pom.xml └── src/ └── test/ ├── java/ │ ├── factory/ │ │ ├── DriverFactory.java │ └── tests/ │ └── LoginTest.java


Step 1: Add below maven dependencies in pom.xml

<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.18.1</version>
    </dependency>
</dependencies>

Step 2: DriverFactory.java

package factory;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class DriverFactory {

    public static WebDriver getDriver(String browserType) {
        WebDriver driver = null;

        switch (browserType.toLowerCase()) {
            case "chrome":
                driver = new ChromeDriver();
                break;

            case "firefox":
                driver = new FirefoxDriver();
                break;

            default:
                throw new IllegalArgumentException("❌ Unsupported browser: " + browserType);
        }

        return driver;
    }
}


Step 3: LoginTest.java

package tests;

import factory.DriverFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;

public class LoginTest {

    @Test
    public void testLoginWithFactoryPattern() {
        // Get browser from factory
        WebDriver driver = DriverFactory.getDriver("chrome");

        driver.get("https://example.com/login");

        // Perform login
        driver.findElement(By.id("username")).sendKeys("user1");
        driver.findElement(By.id("password")).sendKeys("pass123");
        driver.findElement(By.id("login")).click();

        // Add assertions here if needed

        driver.quit();
    }
}


Summary

ComponentRole
DriverFactoryCreates WebDriver objects based on input
LoginTestCalls factory to get a browser driver
TestNG (optional)For structured test execution


Extendability

You can extend DriverFactory to support:

  • Edge, Safari, RemoteWebDriver, Headless Chrome

  • Configuration via .properties or JSON

  • WebDriverManager support (auto-managing drivers)

No comments:

Post a Comment