Selenium WebDriver: Page Object Pattern and PageFactory

Written by Sergei Terekhov |
Wednesday, 12 March 2014

How does it work?

Page Object Pattern is a pattern that displays user interface as a class. In addition to user interface, functionality of the page is also described in this class. This provides a bridge between page and test.

Why should it be used?

Here are the main advantages of Page Object Pattern using:

Simple and clear tests.

Good support of tests, because everything is stored in one place.

Easy creation of new tests. In fact, tests can be created by a person not knowing the features of automation tools.

Simple example of using Page Object Pattern and PageFactory in Selenium WebDriver.

Here we use the annotation FindBy for making the WebElement object to know to which element it belongs on web page (for example helloText belongs to the element whose attribute is name = text, and exitButton belongs to the element whose attribute is name = exit)

For example, in the above classes, we used the following description of the elements on the page:

@FindBy(how = How.NAME, using = "text")
private WebElement helloText;

But as we use PageFactory, code can be written as follows:

private WebElement text;

where text will refer to an element with the attribute name = text

What’s going on?

When we initialize the page using PageFactory, then, if annotation FindBy is not specified, PageFactory searches for elements on the page which name or id attributes match the name of WebElement. As a result, we actually do not have to worry about searching for elements on the page. If the element will appear on the page, so when we turn to it, it will be initialized.

Also, if we know that element is always present on the page, it is best to use the following declaration: