Search code examples
javaselenium-webdriverautomationpom.xmlpageobjects

Can i use PageFactory.initElements to create an object while WebDriver isn't direct (yet) to the page where the WebElements are stored


My question is about Page Object Model in selenuim. I will try to explain myself by an example Let's say i have 2 site. The first one (www.aaa.com) that has a button that clicking on him take us to the second url (www.bbb.com) For both pages i have a class (AAA,BBB) with the elements that are relevant for each of them. Now i have the following code:

@BeforeClass
public void openBrowser() {
    WebDriverManager.chromedriver().setup();
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.navigate().to("http://www.aaa.com");
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

    AAA a= PageFactory.initElements(driver, AAA.class);
    BBB b = PageFactory.initElements(driver, BBB.class);
    
}

My question is: does the last line of code: BBB b = PageFactory.initElements(driver, BBB.class); will throw an exception since the object driver is currently set to work with http://www.aaa.com and therefore when trying to find elements from http://www.bbb.com we will get an exception saying: "NoSuchElement"? According to my try it doesn't happen but it is very surprise for me and i really want to understand how does it work correctly? I was sure that the last line should be written only after moving to the second page (http://www.bbb.com)


Solution

  • PageFactory.initElements will not throw NoSuchElement exception. The reason is, initElements will not do findElement call but will initialize element object with element proxy.