PageFactory, components and fluent style
PageFactory initialises fields annotated with @FindBy as proxies through PageFactory.initElements, but new projects more often use transparent By fields. The proxy hides the lookup, cannot parameterise a locator and gives a NullPointerException without initElements. Components work inside a root element and find that root anew each time. Fluent chains are kept short so it is clear which step failed.
Selenium · Page Object
One line forgotten in a constructor and a NullPointerException instead of a clear error. Which line?
A beginner wrote a Page Object with @FindBy annotations, as in an old tutorial, ran the test and got a NullPointerException on the very first field. Nobody filled the field: PageFactory.initElements was not called. The mistake is simple but characteristic: PageFactory replaces fields with proxies through reflection, and when something goes wrong it is harder to diagnose than a plain field with By. The lesson covers how PageFactory works, why teams move away from it, how to organise components and when the fluent style helps and when it hurts.
How it works and why. PageFactory is a Selenium helper class: fields with @FindBy are initialised by calling PageFactory.initElements(driver, this). Each field becomes a proxy that looks the element up on every access (with @CacheLookup only once, and then the element may go stale, see the lesson “StaleElementReferenceException and other common interaction exceptions”). So the proxy hides the lookup from you, and the code looks like work with an ordinary WebElement.
public class LoginPage {
@FindBy(id = "email") private WebElement email;
@FindBy(id = "password") private WebElement password;
public LoginPage(WebDriver driver) {
PageFactory.initElements(driver, this);
// without this line the fields stay null
}
public void typeEmail(String value) {
email.sendKeys(value); // NullPointerException without initElements
}
}
Hence both the benefit (less boilerplate) and the price: the behaviour is hidden and errors are not obvious. That is why teams usually move to the transparent style:
- forgot
initElements: you getNullPointerExceptioninstead of a clear error; - a locator cannot be parameterised (a table row by name, a button by text): separate methods with
Byare needed, and PageFactory loses its point; - reflection and proxies complicate debugging and composition, while the gain over a
Byfield is minimal; - the Selenium documentation does not list PageFactory among the recommended practices: its description sits in the legacy section.
Two ways to declare elements
@FindBy
Less code, but proxies and reflection. The locator is static, an initialisation error shows only as NullPointerException.
By + driver
Explicit code: you see when the element is looked up, and it is easy to add a wait or a parameter.
Example: a transparent style with a parameterised locator. A Page Object on By fields with a method PageFactory cannot express:
public class OrdersPage {
private final WebDriver driver;
private final By rows = By.cssSelector("table.orders tr.item");
public OrdersPage(WebDriver driver) { this.driver = driver; }
// a parameterised locator: not possible with PageFactory
public OrdersPage cancelOrderOf(String customer) {
By cancel = By.xpath("//tr[td[normalize-space()='" + customer
+ "']]//button[@data-action='cancel']");
new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.elementToBeClickable(cancel))
.click();
return this;
}
public int rowCount() {
return driver.findElements(rows).size();
}
}
The row locator is built from the name, the element is found during the action and the clickability wait lives in the method: the test only calls cancelOrderOf("Ivan"). Names that go into XPath need escaping if they may contain quotes; for test data with a controlled set this is usually not needed.
Components. A header, a side menu, a modal, a table row are separate classes that work inside a root element (WebElement is also a SearchContext), not the whole page. They are reused in many Page Objects, and a search inside the root does not mix up with identical elements in another part of the page.
public class HeaderComponent {
private final WebDriver driver;
private final WebElement root; // the component root, not the page
public HeaderComponent(WebDriver driver, WebElement root) {
this.driver = driver;
this.root = root;
}
public SearchPage search(String text) {
root.findElement(By.name("q")).sendKeys(text + Keys.ENTER);
return new SearchPage(driver);
}
}
public class DashboardPage {
private final WebDriver driver;
public DashboardPage(WebDriver driver) { this.driver = driver; }
public HeaderComponent header() {
// the root is found anew each time: it may be re-rendered
return new HeaderComponent(driver,
driver.findElement(By.cssSelector("header[role='banner']")));
}
}
The page finds the component root anew each time: if it were kept in a field for long, it would go stale after a re-render.
Fluent style. A method returns this or the next page, and the scenario reads as a chain.
// fluent style: each method returns this or the next page
// LoginPage.open(driver) opens /login and returns new LoginPage(driver)
CartPage cart = LoginPage.open(driver)
.loginAs("user@example.com", "secret")
.openCatalog()
.addToCart("Notebook")
.openCart();
// another test: where a check is needed, break the chain with a variable
DashboardPage dashboard = LoginPage.open(driver).loginAs("user@example.com", "secret");
CatalogPage catalog = dashboard.openCatalog();
assertTrue(catalog.hasProduct("Notebook"));
CartPage cart2 = catalog.addToCart("Notebook").openCart();
This is convenient, but long chains are hard to debug: in the stack trace you see only the line number of the whole expression and it is not clear which step failed. So chains are broken with variables where a check is needed and kept to three or four calls.
Limits and alternatives. Page Object is not the only way to structure tests. For scenarios with many actors and user actions there is Screenplay, and in small suites helper functions are enough. Components are needed when a block really repeats; for a single page they only complicate things. PageFactory is not forbidden, and existing code with it works, so there is no point rewriting it without a reason, but for new classes By fields are simpler.
Common mistakes.
@CacheLookupon an element that is re-rendered: after the first update aStaleElementReferenceExceptionappears.- A component that looks for elements through
driverinstead of its root: matches appear with identical elements elsewhere on the page. - A chain of ten calls: a failure at the fifth step is hard to tell from one at the eighth.
- Mixing both styles in one project without a rule: some classes with proxies, some with
By, and every new author guesses how to write.
Check yourself
A test fails with NullPointerException on email.sendKeys(...) in a Page Object with @FindBy. What was most likely forgotten, and how does it differ from a By field?
Answer
PageFactory.initElements(driver, this) was not called in the constructor, so the field stayed null. A By field is initialised at once, and lookup problems show up as NoSuchElementException with a clear locator rather than NullPointerException.
Why does HeaderComponent look for elements through root.findElement(...) rather than driver.findElement(...)?
Answer
A search inside the root is limited to the component subtree: identical elements in another part of the page (a second search field in the footer) are not confused. The same component can also serve several instances on a page by passing a different root.
@FindBy through initElements. A component is a separate class for a repeated part of the page, and the fluent style returns this or the next page. Middle/Senior: In new projects I use By fields and explicit methods with waits: PageFactory hides the lookup behind a proxy, cannot parameterise a locator and is hard to diagnose. Components work inside a root and find it anew each time, and I keep fluent chains short and break them where checks are needed.