Search code examples
javaseleniumselenium-webdrivertestngpage-factory

Code not executing when placed in separate test classes


I am wring a PageFactory framework for a website using maven+TestNG, I have page wise PageObject classes where all web elements and actions specific to page are present like LoginPageObject, AccountSelectionPageObject...
I have a class "Base" where the common elements like WebDriver, Logger are present. I have a class "BasePage" where the common actions like click, scroll, select, refresh... are present

MyTestng.xml is having separate <class> entry for both all individual pages. It's just that I am initializing the browser object in @BeforeSuiit and stored/placed it in the Base class which is being extended in my Test classes Below is the flow/arch I came up for my project. enter image description here Issue:

I have multiple @Test in each of my test classes. When my Test classes are executed individually, all @Test script executed, but when I execute them continuously, i.e. my testng file have separate entries for all my test classes, my execution fails. Error says unable to find element on page, I have wait statements, but still it's not working.

I have tried debugging code, but not able to find the reason as the flow stops on starting of second page with exception saying element not found

Code:

@FindBy(id="listAccounts")
WebElement accountDropdown;

public void selectAccount(){
    logger.info("Selecting Account");
    implicitwait(10);

    Select dropdown = new Select(accountDropdown);
    logger.info("Drop down is multiple::"+ dropdown.isMultiple());
}

Expected:
Code should execute completely even when separated code page wise.

Actual:
When I have all pages code in one test class, code executed. But when I place them separately in page wise test class, element not found exception is thrown.

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"listAccounts"}

Solution

  • In POM using PageFactory framework, one should initialise PageFactory in Constructor of PageClasses. Please find below code snippet which might work in your case.

    public class LoginPage extends TestBase {
    
    public LoginPage() {
        PageFactory.initElements(driver, this);//Here driver is initialised in TestBase class and inherited in LoginPage class
    }
    //your code
    
    @FindBy(id="listAccounts")
    WebElement accountDropdown;
    
    public void selectAccount(){
    logger.info("Selecting Account");
    implicitwait(10);
    Select dropdown = new Select(accountDropdown);
    logger.info("Drop down is multiple::"+ dropdown.isMultiple());
    }
    }