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?
| Advantage | Description |
|---|---|
| Centralized object creation | All drivers created in one place |
| Scalable | Easily add support for new browsers |
| Clean code | Avoids if-else or switch clutter in tests |
| Promotes abstraction | Clients don’t know the exact class being used |
Example: Factory Pattern for Browser Initialization
Project Structure
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
| Component | Role |
|---|---|
| DriverFactory | Creates WebDriver objects based on input |
| LoginTest | Calls 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
.propertiesor JSONWebDriverManager support (auto-managing drivers)
No comments:
Post a Comment