Middle
What is the significance of Page Factory in Selenium?
sobes.tech AI
Answer from AI
Page Factory in Selenium is a pattern and tool for simplifying the initialization of page elements in tests. It allows declaring web elements using annotations (e.g., @FindBy), and then automatically initializes them when creating a page object.
The value of Page Factory:
- Improves code readability and maintainability, as elements are described centrally.
- Enables lazy loading of elements, which increases test performance.
- Reduces boilerplate code for element lookup.
Example in 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();
}
}
Thus, Page Factory simplifies working with elements and makes tests more structured.