Testing / Selenium Interview questions
How do you implement the Page Object Model with PageFactory in Selenium?
The Page Object Model wraps a page's elements and interactions in a class; PageFactory is Selenium's built-in helper for initializing those elements using annotations instead of manual findElement calls in a constructor.
public class LoginPage { WebDriver driver; @FindBy(id = "email") WebElement emailField; @FindBy(id = "password") WebElement passwordField; @FindBy(css = "button[type='submit']") WebElement loginButton; public LoginPage(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); } public void login(String email, String password) { emailField.sendKeys(email); passwordField.sendKeys(password); loginButton.click(); } }
PageFactory.initElements() uses Java reflection and dynamic proxies to lazily locate each @FindBy field the first time it's actually used, rather than eagerly resolving every element the moment the page object is constructed - which helps somewhat with elements that don't exist yet at construction time, though it doesn't make the fields immune to StaleElementReferenceException once resolved.
More Related questions...