Q:

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);
    }
1
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();
  }
}
0
public class BasePage {
  @FindBy(id= "username") private WebElement userName;
  @FindBy(id= "password") private WebElement password;
  @FindBy(id= "login") private WebElement loginBtn;

  public void userLogin(String userName, String password) {
    userName.sendKeys(userName);
    password.sendKeys(password);
    loginBtn.click();
  }
}
0
/*** 
* Constructor 
* @param driver an instance of WebDriver 
*/
public int TimeoutValue = 30;
public SearchResultsPage(Webdriver driver) { 
    PageFactory.initElements(new AjaxElementLocatorFactory(driver, TimeoutValue), this);
}
0

New to Communities?

Join the community