</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

What is PageFactory in Selenium?

PageFactory is a Selenium support class that uses @FindBy annotations to initialize web elements automatically.

Answer

PageFactory extends POM by using @FindBy annotations and lazy element initialization, making code cleaner.

Full PageFactory example:

Java
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class LoginPage {

    @FindBy(id = "username")
    private WebElement usernameField;

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

    @FindBy(css = ".btn-login")
    private WebElement loginButton;

    @FindBy(xpath = "//span[@class=''error-msg'']")
    private WebElement errorMessage;

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

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

    public String getError() {
        return errorMessage.getText();
    }
}

POM vs PageFactory:

POM (By)PageFactory (@FindBy)
Element initOn each callOnce at initialization
SyntaxMore verboseAnnotation-based
Lazy loadingYesYes
Best forDynamic pagesStable pages

Follow AutomateQA

Related Topics