Sobes.tech
Junior — Middle

Can you explain what the Page Factory pattern is and how it is used in test automation?

sobes.tech AI

Answer from AI

The Page Factory pattern is an approach in test automation that simplifies working with web page elements within the Page Object pattern.

It allows declaring web elements using annotations, and then automatically initializing them through a special factory method. This enhances the readability and maintainability of tests.

For example, in Selenium WebDriver with Java:

public class LoginPage {
    @FindBy(id = "username")
    private WebElement usernameInput;

    @FindBy(id = "password")
    private WebElement passwordInput;

    @FindBy(id = "loginBtn")
    private WebElement loginButton;

    public LoginPage(WebDriver driver) {
        PageFactory.initElements(driver, this);
    }

    public void login(String user, String pass) {
        usernameInput.sendKeys(user);
        passwordInput.sendKeys(pass);
        loginButton.click();
    }
}

Here, PageFactory.initElements initializes all elements marked with the @FindBy annotation, eliminating the need to write manual element search code in each method.