Page Factory in Selenium WebDriver

Hello friends! in our previous tutorial on Page Object Model, we studied the POM design pattern. We covered POM’s advantages and its implementation in Selenium WebDriver. In this tutorial, we will study Page Factory in Selenium. PageFactory is an in-built implementation of the Page Object Model given by Selenium WebDriver.

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 Page Factory in Selenium

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 the same (as stated in the 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();
    }
}

With this, we have come to an end of this tutorial on – Page Factory in Selenium. Check out the complete selenium tutorial here – Selenium Tutorial


1 thought on “Page Factory in Selenium WebDriver”

Leave a Comment