PO Tutorial Lesson 4: Modelling Page Behaviour More Accurately


Modelling Page Behaviour More Accurately

The main goal of the page object model is to abstractly represent each page of the website as accurately as possible.

A good practice is to not only write classes for each page, but also for features of the page that are not always present. Such features include dialogs, alerts, and subpages.


In this example we see that the method that will redirect the user to a different page within the website will return the page object for the destination page. By returning page objects we make the code much more readable. This will also make it harder to get confused about which page your test should have opened at that point in time.


public CountryPage searchCountry(String countryName) {
    getElement(searchLocatorXPath).sendKeys(countryName + Keys.ENTER);
    return new CountryPage(driver);

The following code shows how this method will now be used in a test.

CountryPage francePage = homePage.searchCountry("France");

In this test we want to test whether the Capital city as shown on Wikipedia's "France" page is correct. So I have added a getCapital() method to the CountryPage class.

public String getCapital() {
    return getElement(capitalStringLocator).getText();

Note: Sometimes there is so little functionality on a dialog, alert or subpage that it is not worth writing a whole new class for it. In this case it is often better to just include it as functionality in the previous page it was accessible from.

E.g. It might not be worth creating a separate page object for a "terms of service agreement" (TOS) dialog, so you could include the functionality to accept TOS as a method in the page that creates the dialog.

In the next lesson we will be covering the writing of more complex methods to decrease the volume of code even further.