I am a programmer and architect (the kind that writes code) with a focus on testing and open source; I maintain the PHPUnit_Selenium project. I believe programming is one of the hardest and most beautiful jobs in the world. Giorgio is a DZone MVB and is not an employee of DZone and has posted 635 posts at DZone. You can read more from them at their website. View Full User Profile

The Page Object pattern

04.09.2012
| 9572 views |
  • submit to reddit

In the realm of acceptance testing, a possibility for hooking into the application and exercising it end-to-end is to work through a user interface, which nowadays is in more and more cases web-based.

The Page Object pattern is a way to model pages (intended as screens) of a web application as independent objects, and give them several responsibilities:

  • hiding references to HTML element and the DOM, encapsulating the various queries performed by CSS selector or XPath.
  • Providing higher-level operations than the exposure of elements: for example, filling a form with a single method that contains default values for most of the inputs.
  • Extracting frequently made assertions in public methods.
  • Transitioning to the represented page or to a new one; in the latter case, also returning a new Page Object, possibly a different one.

All these responsibilities are extracted and encapsulated in the Page Object to keep actual tests shorter and easier to maintain: the assumption is that an higher-level set of operations like login, posting messages and making assertions will change less frequently and severely than the HTML content of the page.

Technically speaking

The examples I'll make are based on PHPUnit_Selenium, but any library that uses Selenium or other browser drivers works in the same way. In some languages like Java, the Selenium bindings offer utilities for injecting the driver and elements references directly as fields of the object, but it's not necessary to have support from the library to implement this pattern.

Page Objects compose a Session or Driver (depending on which language you are using) or Testcase object, the topmost object available: in theory they can call anything on it, but their job is to hide that global object from the tests.

A Page Object will extract Element objects from this Facade to perform operations on them, but also encapsulate direct calls to any Selenium-related machinery. One class for every type of page is common.

A practical example

In this example, we use two page objects to test a login mechanism:

  • AuthenticationPage provides the capability to login, by compiling the form and submitting it.
  • WelcomePage models the welcome page and adds a page-specific assertion.

This is the test:

<?php
class Tests_PageObjectTest extends Tests_Selenium2TestCase_BaseTestCase
{
    public function testAPageInteractsWithElementsExposingAnHigherLevelApi()
    {
        $page = new Tests_AuthenticationPage($this);
        $welcomePage = $page->username('TestUser')
                            ->password('TestPassword')
                            ->submit();
        $welcomePage->assertWelcomeIs('Welcome, TestUser!');
    }
}

while these are the two classes implementing the pattern:

class Tests_AuthenticationPage
{
    public function __construct($test)
    {
        $test->url('html/test_type_page1.html');
        $this->usernameInput = $test->byName('username');
        $this->passwordInput = $test->byName('password');
        $this->test = $test;
    }

    public function username($value)
    {
        $this->usernameInput->value($value);
        return $this;
    }

    public function password($value)
    {
        $this->passwordInput->value($value);
        return $this;
    }

    public function submit()
    {
        $this->test->clickOnElement('submitButton');
        return new Tests_WelcomePage($this->test);
    }
}

class Tests_WelcomePage
{
    public function __construct($test)
    {
        $this->header = $test->byCssSelector('h2');
        $this->test = $test;
    }
    
    public function assertWelcomeIs($text)
    {
        $this->test->assertRegExp("/$text/", $this->header->text());
    }
}

It's now very easy to write a new test using the Page Objects, covering for example a wrong username or password case. In the case of already existing tests, they become a lot shorter and their language is related to the domain and concepts that the user works with, not on HTML elements and synchronization directly.

Another possibility, not shown here for the lack of necessity, could be handy: implicit waits and other means for synchronization can be hidden by the Page Objects, centralizing this kind of boilerplate code.

Conclusions

An application driver layer (that works through an UI) exposes primitives at an higher level of abstraction than HTML element manipulation, but this intermediate level is easy to introduce and removes most of the duplication related to Selenium (or your tool for driving browsers and UIs).

Page Objects preserve user experience and movement through screens alternated by actions. If this level is not sufficient to remove duplication from tests, you can abstract even more and extract given/when/then methods, like:

$this->loggedAs('giorgio');
$this->postMessage('My title', 'lorem ipsu....);
$this->assertMessagePresentInHomepage('My title');

 

Published at DZone with permission of Giorgio Sironi, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)