How to use PageFactory in Selenium Page object model

Test Automation frameworks based on Page object model design pattern  requires the locators to be kept separate from the methods which access them. Now this can be achieved in many ways. In this article we will see how to use PageFactory to maintain locators in Page Object Model. If you are interested to learn more or just want to refresh your memory, you can see

How to use By class to store locators in Selenium Page Object Model

PageFactory is an inbuilt feature of Selenium WebDriver, which is an implementation of Page Object Model. It acts like a starting kit to your page objects and initialises the page objects through the command  PageFactory.initElements(driver, this); 

Every page object has this command in their constructor along with the command for setting the driver. this.driver=driver;

To understand more how to use the PageFactory, see the code snippet provided below.

Example Test Scenario

In order to understand this concept, we have taken a simple scenario which is scripted in the class .

  • Open google search application: url-
  • Enter a keyword on google search page.
  • Press key Enter

Sample Class Using PageFactory

Apart from xpath, You can use tagName, partialLinkText, name, linkText, id, css, className  as locator types in your page objects with @FindBy. You can use any type of locator and initialise a webelement. In your page object, represent every webelement by a name such as searchBox and firstResult in the above example

Advantages Of PageFactory Over Simple POM

  1. In simple POM, you need to take care of StaleElementReferecneException with the help of your framework design and coding, while this is taken care in the PageFactory.
  2. It relocates a WebElement on the page every time it has to be used, thus avoiding StaleElementReferecneException .
  3. It is more readable and maintenance is effortless.
  4. We don’t need to write driver.findElement everytime we want to perform some operation on a WebElement.

Checkout the code repo

Subscribe for updates