DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. The Page Object pattern

The Page Object pattern

Giorgio Sironi user avatar by
Giorgio Sironi
·
Apr. 09, 12 · Interview
Like (0)
Save
Tweet
Share
15.84K Views

Join the DZone community and get the full member experience.

Join For Free

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');

 

Object (computer science)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Strategies for Kubernetes Cluster Administrators: Understanding Pod Scheduling
  • Mission-Critical Cloud Modernization: Managing Coexistence With One-Way Data Sync
  • Software Maintenance Models
  • How To Set Up and Run Cypress Test Cases in CI/CD TeamCity

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: