I would like to know from the below which is better option for creating the instance of the PageObject class(Ex: LoginPage):-
1) Create an instance of Pageobject class in all the tests and steps (Wherever required)?
LoginPage loginpage = PageFactory.initElements(webDriver, LoginPage.class);
(or)
2) Create a class with a static method to return the instance for the requested PageObject class. In this method, check if the instance is null before creating a new instance for the requested class?
LoginPage loginpage = PageUtil.getPageObject("login");
Please advise.
There are multiple ways to do it. I like to create a BaseClass()
and instantiate the PageFactory.initElements(driver, this);
there. See my gist. Also, the public repository here
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
/**
* Created by Saifur on 2/14/2015.
*/
public class BaseClass {
//global driver instance.
WebDriver driver;
//super constructor
public BaseClass(WebDriver _driver)
{
//assigning driver instance globally.
driver = _driver;
/*Instantiating all elements since this is super class
and inherited by each and every page object */
PageFactory.initElements(driver, this);
}
}