PageFactory initialization helps create and set up web elements in a simple way. It makes tests easier to read and write.
PageFactory initialization in Selenium Java
public class PageName { @FindBy(id = "locatorValue") private WebElement elementName; public PageName(WebDriver driver) { PageFactory.initElements(driver, this); } }
The @FindBy annotation tells Selenium how to find the element.
PageFactory.initElements(driver, this) initializes all elements annotated with @FindBy.
public class LoginPage { @FindBy(id = "username") private WebElement usernameField; @FindBy(id = "password") private WebElement passwordField; @FindBy(id = "loginBtn") private WebElement loginButton; public LoginPage(WebDriver driver) { PageFactory.initElements(driver, this); } }
public class HomePage { @FindBy(css = ".profile-link") private WebElement profileLink; public HomePage(WebDriver driver) { PageFactory.initElements(driver, this); } }
This test script opens a browser, navigates to a login page, initializes the page elements using PageFactory, performs a login, prints a message, and closes the browser.
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; 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(id = "loginBtn") private WebElement loginButton; public LoginPage(WebDriver driver) { PageFactory.initElements(driver, this); } public void login(String username, String password) { usernameField.sendKeys(username); passwordField.sendKeys(password); loginButton.click(); } } class TestLogin { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get("https://example.com/login"); LoginPage loginPage = new LoginPage(driver); loginPage.login("user1", "pass123"); System.out.println("Login attempted"); driver.quit(); } }
Always call PageFactory.initElements(driver, this) in the page class constructor.
Use meaningful names for web elements to keep tests clear.
Make sure locators are unique and stable to avoid flaky tests.
PageFactory initialization simplifies element setup in Selenium tests.
Use @FindBy annotations and call initElements in constructor.
This approach improves code readability and maintenance.
Practice
PageFactory.initElements() in Selenium Java?Solution
Step 1: Understand the role of PageFactory
PageFactory is used to initialize WebElements in Page Object Model classes.Step 2: Purpose of initElements method
TheinitElementsmethod scans the class for @FindBy annotations and initializes those elements.Final Answer:
To initialize all WebElements annotated with @FindBy in a Page Object -> Option CQuick Check:
PageFactory.initElements initializes elements [OK]
- Confusing initElements with WebDriver start or stop
- Thinking initElements executes JavaScript
- Assuming initElements closes the browser
Solution
Step 1: Recall the method signature
The correct method call isPageFactory.initElements(WebDriver driver, Object page).Step 2: Match parameters in constructor
Inside the constructor,driveris passed first, thenthisrefers to the current Page Object instance.Final Answer:
PageFactory.initElements(driver, this); -> Option AQuick Check:
Correct parameter order is driver, then this [OK]
- Swapping driver and this parameters
- Calling non-existent methods like startElements
- Omitting PageFactory class name
loginButton.isDisplayed() is called after PageFactory initialization?public class LoginPage {
@FindBy(id = "loginBtn")
private WebElement loginButton;
public LoginPage(WebDriver driver) {
PageFactory.initElements(driver, this);
}
}
// In test method:
LoginPage page = new LoginPage(driver);
boolean visible = page.loginButton.isDisplayed();
System.out.println(visible);Solution
Step 1: Check field visibility modifier
TheloginButtonis declaredprivate, so it cannot be accessed directly from outside theLoginPageclass in the test method.Step 2: Identify the compilation issue
page.loginButton.isDisplayed()causes a compilation error; private fields require public getter methods for external access. PageFactory initializes the field but does not change its visibility.Final Answer:
Compilation error due to missing getter for loginButton -> Option BQuick Check:
Private fields need public getters for access [OK]
- Assuming direct access to private fields works after PageFactory init
- Expecting runtime false or NullPointerException instead of compile error
- Believing PageFactory overrides Java access modifiers
public class HomePage {
@FindBy(name = "searchBox")
WebElement searchInput;
public HomePage(WebDriver driver) {
initElements(driver, this);
}
}Solution
Step 1: Check method call syntax
The methodinitElementsmust be called with the class namePageFactoryasPageFactory.initElements(...).Step 2: Verify other code parts
The locator strategy 'name' is valid, WebElement can be package-private, and constructor can have parameters.Final Answer:
Missing PageFactory class before initElements method call -> Option DQuick Check:
Always prefix initElements with PageFactory [OK]
- Calling initElements without PageFactory prefix
- Thinking locator strategy 'name' is invalid
- Assuming WebElement must be private
- Believing constructors cannot have parameters
Solution
Step 1: Understand Page Object best practices
WebElements should be private and annotated with @FindBy for clear locators and encapsulation.Step 2: Proper initialization
PageFactory.initElements(driver, this) should be called in the constructor to initialize elements automatically.Final Answer:
Declare WebElements with @FindBy, initialize them in constructor using PageFactory.initElements(driver, this), and keep elements private -> Option AQuick Check:
Private elements + @FindBy + initElements in constructor = best practice [OK]
- Making WebElements public exposing internals
- Skipping PageFactory.initElements call
- Initializing elements manually in tests
- Using static WebElements without context
Ready to prove it?
Pass the test and this pattern moves unknown
