0

I am looking to instantiate my page classes to access methods from testng classes with out using PageFactory.initElements() or new Operator. I want to make my test code look clean and neat.

Currently I am using PageFactory.initElements() method to initialize my page classes for each class in all testng classes which leads to code unreadable and not clean.

HomePage homePage = PageFactory.initElements(driver, HomePage.class);

Are there any annotations to inject page classes automatically?

  • initElements() can, and probably should be performed inside the page object itself. I'm not sure why you think that "new" does not make code look clean and neat. – Bill Hileman Jan 28 '19 at 15:50

1 Answers1

0

Step1 - Create a static driver class

public sealed class Driver
{
    [ThreadStatic]
    private static IWebDriver driver = null;


    public static IWebDriver Instance
    {
        get
        {
            if (driver == null)
            {
                driver = new ChromeDriver();
            }
            return driver;
        }
    }

    public static void Testcleanup()
    {           
        driver.Quit();
        driver = null;

    }
}

Step 2 - Create a base class where pageobjects would be initialized

public class TestBase
{
    private LoginPage loginPage;
    private HomePage homePage;

    public TestBase()
    {
        loginPage = new LoginPage();
        homepage = new HomePage();            
        PageFactory.InitElements(Driver.Instance, loginPage);
        PageFactory.InitElements(Driver.Instance, homePage);
    }

    public static LoginPage Login
    {
        get { return Instance.loginPage; }
    }


    public static HomePage Home
    {
        get { return Instance.homePage; }
    }

    private static TestBase Instance
    {
        get
        {
            return new TestBase();
        }
    }
}

Step3 : Finally use the base class in test class

   [TestClass]
public class PageInitTest : TestBase
{
    [TestMethod]
    public void PageInit()
    {

        Driver.Instance.Navigate().GoToUrl("url");
        Login.Email.SendKeys("Demo@gmail.com");  
    }     

}
  • Static driver instance restricts us parallel execution. I think instead of static , we can use design patterns to achieve like above. But I am looking for java annotations for dependency injection. Hope you understand! – Prasad Pasupuleti Jan 28 '19 at 10:26
  • Your question did not mention anything about running it parallel. The solution i gave was to address the question raised. If you want to run tests in parallel, refer - https://stackoverflow.com/questions/46698136/how-to-run-my-selenium-test-methods-in-parallel-using-testng – Anant Krish Jan 28 '19 at 11:52