While developing a script using Page Object Model, we use PageFactory.initElements(driver,this) to initialize the webelement.
How this is done and why we pass parameters 'driver' and 'this' ?

  • I closed this as a duplicate of the other, identical question. If the "driver and this" part makes this a substantially different question, please let me know. – corsiKa May 11 '16 at 16:27

Page Factory Pattern is like an extension to Page Object Model , but Page Factory is much enhanced model. To start with, we just need to import package org.openqa.selenium.support.PageFactory

Factory class can be used to make using Page Objects simpler and easier.

We use Page Factory pattern to initialize web elements which are defined in Page Objects.

We should initialize page objects using initElements() method from PageFactory Class as below, Once we call initElements() method, all elements will get initialized. PageFactory.initElements() static method takes the driver instance of the given class and the class type, and returns a Page Object with its fields fully initialized.

public HompePage(WebDriver driver) 
   this.driver = driver; 
   PageFactory.initElements(driver, this);

Now question arise why we use Constructor?

We should preferably use a constructor which takes a WebDriver instance as its only argument or falling back on a no-arg constructor. An exception will be thrown if the class cannot be instantiated.
Page Factory will initialize every WebElement variable with a reference to a corresponding element on the actual web page based on “locators” defined.

Check below code by using Simple POM

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) 

By using using Page Factory:

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) {
| improve this answer | |
  • I would add that this can also be solved by doing it in a main base object and have all pages using POM inherit that class. – Paul Muir May 8 '16 at 12:09
  • How Can you please share the code? – Sandeep Aug 9 '17 at 6:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.