What is Page Object Pattern and why should I use it?

The Page Objects pattern describes any web page in terms of a hierarchical Domain Specific Language (DSL). The application specific DSL helps to hide the page implementation; the test is no longer allowed to directly interact with a given page, but instead uses a framework of classes and methods to accomplish the same goal. This pattern abstracts the implementation details, such as element IDs, into a framework specifically designed for the application being tested.

 The Page Object design pattern provides tests for an interface where a test can operate on that page in a manner similar to the user accessing the page, but by hiding its internals.

 For example, if we build a Page Object test for a login page, then it will provide a method to log in, which will accept the username and password and take the user to the home page of the application. The test need not worry about how input controls are used for the login page, their locator details, and so on.

Tests should use objects of a page at a high level, where any change in layout or attributes used for the fields in the underlying page should not break the test.

Advantages:

  • After implementing the Page Objects pattern, we end up with a framework that describes the application from business point of view. Each action performed by a test using this framework should be easy to comprehend to anyone in the given field. That is to say, a test written for an accounting system that is heavy on the field’s jargon might not be easy to comprehend to the laymen; however, anyone with basic knowledge of the field should understand the intentions of each action.
  • Page Object pattern helps to test the desired behavior of the application using its DSL
  • This pattern helps in enhancing the tests, making them highly maintainable, reducing the code duplication, building a layer of abstraction, and hiding the inner implementation from tests.
  •  A well-implemented and rigid Page Objects framework has one and only way to accomplish any action. This prevents duplicate implementation of the same methods.
  • Since each Page Object is made from multiple smaller objects, such as header section or login form, the smaller objects can be shared between multiple Page Objects.

Disadvantages:

  • Complexity is increased when using Page Objects framework. As the name implies, we can’t just write a simple procedural test, we need to create a framework.
  • Programming design patterns should be followed to make the code consistent and easy to understand. Otherwise, the framework quickly becomes muddled and complex to use and maintain.
  • As with any new tool, it is tempting to get carried away and use it everywhere. It’s tempting to implement a Page Objects framework on a test suite that only has 10 tests; this time could probably have been spent better improving existing code.