Inheriting WebDriver Throughout Your Page Object Classes

Inheriting WebDriver Throughout Your Page Object Classes

I’ve seen (and written) several automation projects where each page class requires a constructor that takes a WebDriver object so that the page classes can access the current browser instance. There’s nothing particularly wrong with this, but I do find it a bit annoying to pass around the WebDriver like a hot potato. Instead, you can use inheritance.

My preferred approach is to create a base test class which defines a WebDriver object, instantiates it, and then sets it in a base page. Subsequent page classes then inherit from the base page, thus automatically having access to the driver.

Notice that here in the base test class, in addition to instantiating the WebDriver, we also create a handle to the base page and set the WebDriver in that page. By doing this, no tests need to touch the WebDriver.

Here’s an example of the Page class

I use the Page class as a base that contains functionality that is available on any page within the application, such as the search and clickCheckoutLink functions. Then any new page object class I create, can simply inherit from this class, thus gaining access to the WebDriver. Notice there’s no need for a constructor that accepts the WebDriver object in this page class.

Here’s an example of a simple test just to make sure everything works. Test classes that extend from BaseTest will not need to instantiate a page class to get started, as they inherit the homePage instance from BaseTest.




I received a question on Twitter asking is there a way to do this without making the WebDriver static.


If using Junit which comes with the Selenium dependencies, their Before and After methods are static and therefore force some things upon us. We can still get around making the WebDriver static but it takes a bit of wizardry. You can essentially make a static instance to the BaseTest class itself, and create a non-default constructor that does what your static setup method would have.


All other classes remain the same. This works, but feels hacky to me, which is why I prefer the first approach. But I understand people’s projects may require different things. Another alternative would be to use TestNG or another assertion tool that does not require static Before and After methods.

Angie Jones
1 Comment
  • Timothy Western

    This is similar to am approach I’ve used several times. It allows a lot of setup to happen consistently through the parent constructor. And it does so while allowing the possibility of extension not for social cases without to much trouble.

    December 23, 2017 at 9:11 am Reply

Post a Comment