I am developing test cases using Selenium and TestNG, and am following the Page Object Model design pattern.

Currently, my page classes look like this (Page1 is just a placeholder, they all have more meaningful names in actuality):

public class Page1 {
    WebDriver driver;
    public Page1(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);

and my test classes look like this:

public class Test {
    private WebDriver driver;
    private Page1 page1;
    private Page2 page2;
    public void setUp() {
        driver = new ChromeDriver();
        page1 = new Page1(driver);
        page2 = new Page2(driver);

where the driver and each page object is declared directly inside the test class, and instantiated in @BeforeMethod.

As you can see, with a lot of page classes, the test class can quickly become cluttered simply by instantiating all of the page objects. I looked around and found that the Google Guice framework could potentially be used to simplify some of these dependencies. i.e. by just requiring
@Inject private Page1 page1; and not needing to call the constructor in the setup method.

However, even after reading some of the documentation online I am unsure of how to accomplish this. Does anyone have any knowledge of how to do something like this (or if it is even possible)? If not, is there an alternative way I can simplify and improve the readability of my test classes? Or is there even a point to doing what I'm trying to do?


1 Answer 1


Firstly, you can remove any reference to the driver in the tests by creating a BasePage class:

class BasePage {
protected static WebDriver driver = null;

BasePage() { 
   if (driver == null) driver = new ChromeDriver(); 

class Page1 extends BasePage {
   Page1() { super(); }

Secondly, @Before/@After should not carry test logic, but to prepare external components for the tests. When one read the test, it should be clear what is going on.

test() {
    HomePage home = new LandingPage().login("name", "password");

Therefore, you do not need to instantiate pages in the @BeforeMethod, but on the specific tests that use these pages. If you feel the need to abstract the construction of the pages, the Factory Pattern may help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.