Search code examples
selenium-webdrivertestng-eclipsepage-factory

Pagefactory init elements function to be declared once in code for code optimization


I am automating my project using page object model. But I noticed that whenever I am writing two different scenarios to be automated for same page object, I need to initialize elements for that test case each time I write the test case using Pagefactory.initElements method. Is there any way so that this can be initialized only once and can be reused in all test cases ?

I tried to make reference variable i.e. for e.g. "manorgpom ort=PageFactory.initElements(getdriver(), manorgpom.class);" ort to be static but it is giving null pointer exception. I initialized them outside my test cases and made the reference variable static but to no success.

    @Test(priority=3)
public void orgact() throws Exception {
    manorgpom ort=PageFactory.initElements(getdriver(), manorgpom.class);
    getdriver().manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    ort.actorg();
    Thread.sleep(5000);
}

@Test(priority=4)
public void orgadd() throws Exception{
    manorgpom ort=PageFactory.initElements(getdriver(), manorgpom.class);
    getdriver().manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    ort.addorg();
    Thread.sleep(10000);
}

If you see above I need to initialize web elements each time I write test case. Each time I need to mention "manorgpom ort=PageFactory.initElements(getdriver(), manorgpom.class);". I want to optimize this.

This is the manageorgpom class snippet.

    public class manorgpom extends Basetest{
@FindBy(xpath="//*[@href='/organization']")
WebElement orglink;

@FindBy(xpath="//*[@class='anticon anticon-filter']")
WebElement filter;

@FindBy(xpath="//*[@placeholder='e.g. High School USA']")
WebElement filternametxt;

@FindBy(xpath="//*[text()='Activate']")
WebElement activatelink;

@FindBy(xpath="//*[@placeholder='e.g. Johnny']")
WebElement contactfirstname;

When I made the ort reference variable static, I am getting java.lang.nullPointerException each time I run the suite. Please help me.


Solution

  • Thats because your webDriver is geting instantiated everytime. You need to make it singleton and use only one instance of the webDriver.

    public class driverSingleton { 
    private static final webDriver instance = new ChromeDriver();   //just for example 
    //private constructor to avoid client applications to use constructor private EagerInitializedSingleton(){} 
    public static driverSingleton getInstance(){ return instance;
    
    }