What is PageFactory?
PageFactory is elegance furnished by Selenium WebDriver to aid the Page Object layout pattern. It makes dealing with “Page Objects” less complicated and optimized with the aid of presenting the subsequent-
- @FindBy annotation
- initElements technique
@FindBy-
@FindBy annotation is used in PageFactory to discover and declare internet factors using unique locators. Here, we bypass the attribute used for locating the net detail together with its fee to the @FindBy annotation as parameter after which claim the detail. Example-
@FindBy(id="elementId") WebElement element;
In the above example, we've used ‘identification’ attribute to locate the web element ‘element’. Similarly, we will use the following locators with @FindBy annotations.
- ClassName
- css
- call
- xpath
- tagName
- linkText
- partialLinkText
initElements()-
The initElements is a static technique of PageFactory class which is used in conjunction with @FindBy annotation. Using the initElements approach we are able to initialize all of the net factors positioned through @FindBy annotation. Thus, instantiating the Page lessons easily.
initElements(WebDriver driver, java.lang.Class pageObjectClass)
Code Snippet for PageFactory
Below is a code snippet with a demo Page elegance. Here, the internet factors are located by way of @FindBy annotation and the initElements technique is invoked within the constructor of the PageFactoryDemoClass.
PS: The implementation of test instructions 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();
}
}