PageFactory in Selenium WebDriver


Hello friends! in our previous tutorial on Page Object Model, we studied about POM design pattern, its advantages and implementation in Selenium WebDriver. In this tutorial, we will study about PageFactory, an enhanced implementation of Page Object Model.

What is PageFactory?

PageFactory is class provided by Selenium WebDriver to support the Page Object design pattern. It makes handling "Page Objects" easier and optimized by providing the following-

  • @FindBy annotation
  • initElements method

@FindBy-

@FindBy annotation is used in PageFactory to locate and declare web elements using different locators. Here, we pass the attribute used for locating the web element along with its value to the @FindBy annotation as parameter and then declare the element. Example-

@FindBy(id="elementId") WebElement element;

In the above example, we have used 'id' attribute to locate the web element 'element'. Similarly, we can use the following locators with @FindBy annotations.

  • className
  • css
  • name
  • xpath
  • tagName
  • linkText
  • partialLinkText

initElements()-

The initElements is a static method of PageFactory class which is used in conjunction with @FindBy annotation. Using the initElements method we can initialize all the web elements located by @FindBy annotation. Thus, instantiating the Page classes easily.

initElements(WebDriver driver, java.lang.Class pageObjectClass)

Code Snippet for PageFactory

Below is a code snippet with a demo Page class. Here, the web elements are located by @FindBy annotation and the initElements method is invoked in the constructor of the PageFactoryDemoClass.
PS: The implementation of test classes will remain same (as stated in Page Object Model tutorial).

public class PageFactoryDemoClass {

    WebDriver driver;

    @FindBy(id="search")
    WebElement searchTextBox;
   
    @FindBy(name="searchBtn")
    WebElement searchButton;

    //Constructor invoking initElements method
    public PageFactoryDemoClass(WebDriver driver){
        this.driver = driver;
        
	//initializing all the web elements located by @FindBy
        PageFactory.initElements(driver, this);
    }
    
    //Sample method of the page class
    public void search(String searchTerm){
        searchTextBox.sendKeys(searchTerm);  
        searchButton.click();
    }
}