Search code examples
selenium-webdriverpageobjectspage-factory

In Selenium, is it good to reuse same instance of the Page class multiple times in the same test method or should I create new instance?


I need to test the website: https://www.rediff.com using PageFactory pattern.
My test method does the following steps:
Step-1. Goto Rediff home page https://www.rediff.com/
Step-2. Click on Sign-in button
Step-3. Enter the username and password and click on Submit button
Step-4. Click on rediff.com link at the extreme top left which will take the user back to Rediff home page. Now enter the text in the search bar and click on Search button

Below is the test class:

    public class RediffLoginTest extends BaseClass
    {
    
        @Test
        public void loginAndSearch() throws InterruptedException
        {

//          Step-1
            getDriver().navigate().to("https://www.rediff.com");
    
//          Step-2
            RediffHomePage rhp = new RediffHomePage();
            PageFactory.initElements(getDriver(), rhp);
            rhp.signIn().click();
    
//          Step-3
            RediffLoginPage rlp = new RediffLoginPage();
            PageFactory.initElements(getDriver(), rlp);
            rlp.enterEmailID().sendKeys("hello");
            rlp.enterPassword().sendKeys("demopass");
            rlp.submitLogin().submit();
    
//          Step-4
            rlp.goToHomePage().click();
            rhp.enterSearchText().sendKeys("demo");
            rhp.submitSearch().click();
    
        }
    
    }

As per the Step-4 explained above, it takes me back to Rediff home page. I have already created an object rhp of RediffHomePage in Step-2. So, my question is, for the Step-4, is it good to reuse this same object rhp as shown in the above code or should I create another object of the same page class in the same test method for e.g. say rhp1 of RediffHomePage as shown in the below code ?

RediffHomePage rhp1 = new RediffHomePage();
PageFactory.initElements(getDriver(), rhp1);
rhp1.enterSearchText().sendKeys("demo");
rhp1.submitSearch().click();

Solution

  • If possibly, in such situations you definitely should reuse the existing objects, not to create again and again new redundant objects.