page factory in selenium code example
Example 1: page factory in selenium
PageFactory is a class in selenium.
It is used to achieve page factory design pattern,
it helps to initialize the page objects in the
class using initElements methods. When
I create an object from the page class,
pagefactory initializes the webelements
just before interacting this web element.
It means that once you call the element,
PageFactory class will immediately locate the element
and you will not get a staleElementReferenceException.
When a page object is created,
pagefactory driver (because of the constructor)
will be linked to weblements @findby in that page.
public LoginPage(){
PageFactory.initElements(Driver.get(), this);
}
Example 2: page factory class in selenium
PageFactory is a class in selenium.
It is used to achieve page factory design pattern,
it helps to initialize the page objects in the
class using initElements methods. When
I create an object from the page class,
pagefactory initializes the webelements
just before interacting this web element.
It means that once you call the element,
PageFactory class will immediately locate the element
and you will not get a staleElementReferenceException.
Example 3: advantages of page factory in selenium
public class BasePage {
private By username = By.id("username");
private By password = By.id("password");
private By loginBtn = By.name("loginbtn");
public void userLogin(String userName, String password) {
driver.findElement(username).sendKeys("testuser");
driver.findElement(password).sendKeys("testpassword");
driver.findElement(loginBtn).click();
}
}
Example 4: advantages of page factory in selenium
public int TimeoutValue = 30;
public SearchResultsPage(Webdriver driver) {
PageFactory.initElements(new AjaxElementLocatorFactory(driver, TimeoutValue), this);
}