Middle+
Millist mustrit pead kõige olulisemaks pärast Page Object'i?
sobes.tech AI
Vastus AI-lt
Factory Method.
It allows creating objects without specifying the exact class in the client code. This is important for flexibility and extendability of automated tests, for example, when working with different browsers or platforms.
Example of usage in automation context:
Suppose we have an interface WebDriverFactory and its implementations for different browsers (ChromeWebDriverFactory, FirefoxWebDriverFactory). The factory method allows obtaining an instance of the required driver without resorting to conditional structures (if/else) in the test code.
// Factory interface
interface WebDriverFactory {
WebDriver createDriver();
}
// Implementation for Chrome
class ChromeWebDriverFactory implements WebDriverFactory {
@Override
public WebDriver createDriver() {
WebDriverManager.chromedriver().setup();
return new ChromeDriver();
}
}
// Implementation for Firefox
class FirefoxWebDriverFactory implements WebDriverFactory {
@Override
public WebDriver createDriver() {
WebDriverManager.firefoxdriver().setup();
return new FirefoxDriver();
}
}
// Usage in test
public class BaseTest {
protected WebDriver driver;
@BeforeMethod
public void setupTest() {
WebDriverFactory factory = getWebDriverFactory("chrome"); // Get the required factory
driver = factory.createDriver(); // Create driver via factory
driver.manage().window().maximize();
}
private WebDriverFactory getWebDriverFactory(String browser) {
if ("chrome".equalsIgnoreCase(browser)) {
return new ChromeWebDriverFactory();
} else if ("firefox".equalsIgnoreCase(browser)) {
return new FirefoxWebDriverFactory();
}
throw new IllegalArgumentException("Unsupported browser: " + browser);
}
@AfterMethod
public void tearDownTest() {
if (driver != null) {
driver.quit();
}
}
}
Advantages:
- Low coupling: Client code depends only on the factory interface, not on specific implementations.
- Extensibility: Easily add support for a new browser by creating a new factory and modifying the
getWebDriverFactorymethod. - Isolation: The object creation logic is centralized in one place (the factory), simplifying maintenance.