Skip to main content

Using a Base Page Object

Intro​

In a previous tip, we went through creating a simple Page Object to capture the behavior of a page we were interacting with. While this was a good start, it leaves a lot of room for improvement. One of the biggest issues is that there are common actions we will likely need across multiple Page Objects and, with our current approach, we would end up with duplicate code.

Another issue is that we are using Selenium actions directly in the Page Object, which could present some long-term impacts like, such as:

  • the inability to drive your tests with a different driver
  • test maintenance issues when Selenium actions change
  • slower test writing due to the lack of a Domain Specific Language (DSL)

A Solution​

With a Base Page Object (a.k.a. a facade layer) we can abstract all common actions into a central location and leverage them in any Page Object we see fit.

Example​

We are going to take the code from our previous tip (Use a Page Object) and modify it to use a Base Page Object.

The Base Page Object is a simple class that our other Page Objects inherit from. It stores the Selenium WebDriver instance and wraps the common Selenium actions (visit, find, click, type, check if something is displayed, get its text, and wait for it) in a small Domain Specific Language (DSL).

With it in hand, the Dynamic Loading Page Object from the previous tip no longer calls Selenium directly. To show that the same actions are reusable, we also add a Page Object for the login page found on the-internet.

Expected Behavior​

  • Load the Dynamic Loading page, click on start, and assert that Hello World! is displayed
  • Load the login page, log in with valid credentials, and assert that the success message is displayed

Summary​

Now we are in a position to write more Page Objects that leverage common actions without duplication or any Selenium code directly in them.

Hopefully this tip has helped you find your way further down the rabbit hole of Page Objects (in a good way).

Happy Testing!

Special Thanks​

Andrei Solntsev
Contributed the Selenide code for this tip.

Authors​

Dave Piacente
Original creator of Elemental Selenium
Diego Molina
Elemental Selenium maintainer