2
votes

I'm trying to build a Cucumber Java framework in Page Object Model. I have created the base framework and it works fine, but got confused how to initialize the pages. I have noticed that in most of the tutorials they have initialized the pages in constructor itself.

Example:

public LoginPage(WebDriver driver)
{
   this.driver = driver;
   PageFactory.initElements(driver, this);
}

Likewise in all the page classes, they have added initElements method inside constructor itself.

But there are some sites where I noticed that instead of initializing all the pages in constructor, first page they initialized in constructor and for all other pages they initialized at return statement of some method (being executed at last in current page). If method "login" is the last method in LoginPage.java, then it would initialize HomePage as return type.

Example:

public HomePage login(String un, String pw)
{
   ...
   ...
   return PageFactory. initElements(driver, HomePage.class); 
}

My Doubt: Which one is the right way to implement and efficient one?

1

1 Answers

4
votes

There is no "right way". PageFactory.initElements(driver, HomePage.class) creates new instance of the given class (HomePage) and then call PageFactory.initElements(driver, instance); PageFactory source code

public static <T> T initElements(WebDriver driver, Class<T> pageClassToProxy) {
    T page = instantiatePage(driver, pageClassToProxy);
    initElements(driver, page);
    return page;
}

// translate to

HomePage homePage = new HomePage();
PageFactory.initElements(driver, homePage);
return homePage;

Which is the same as calling PageFactory.initElements(driver, this); from the PO constructor.

The main difference is actually in the fact that the method return the next PO, which allow to use method chaining.

With method chaining:

new LoginPage(driver)
    .login()
    .clickOnButton();

And without method chaining:

LoginPage loginPage = new LoginPage(driver);
loginPage.login();

HomePage homePage = new HomePage(driver);
homePage.clickOnButton();

*You can use PageFactory.initElements in the constructor and simply return new HomePage(); to use method chaining.