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.
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 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-
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.
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.
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).