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
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 GoogleSearchPageFactory.java .
- Open google search application: url- www.google.com
- 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
- 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.
- It relocates a WebElement on the page every time it has to be used, thus avoiding StaleElementReferecneException .
- It is more readable and maintenance is effortless.
- We don’t need to write driver.findElement everytime we want to perform some operation on a WebElement.