selenium-webdriverPage Object Model


Introduction

A significant role in automating web sites and web applications involves identifying items on the screen and interacting with them. Items are found in Selenium through the use of locators and the By class. These locators and interactions are put inside Page Objects as a best practice to avoid duplicate code and make maintenance easier. It encapsulates WebElements and suppose to contain behavior and return info on the page (or part of a page in a web app).

Remarks

Page object model is a pattern where we write object oriented classes that serve as an interface to a particular view of web page. We use the methods of that page class to perform the required action. Few years back, we were manipulating the HTML code of webpage in test classes directly which was very difficult to maintain along with brittle to changes in UI.

However, having your code organized in a way of Page Object Pattern provides an application specific API, allowing you to manipulate the page elements without digging around the HTML. The basic Rue of thumb says, your page object should have everything which a human can do on that webpage. For example, to access the text field on a webpage you should a method there to get the text and return string after doing all the modifications.

Few important points you should keep in mind while designing the page objects:

  1. Page object usually should not build only for pages, but you should prefer to build it for significant elements of page. For example, a page having multiple tabs to show different charts of your academics should have same number of pages as the count of tabs.

  2. Navigating from one view to other should return the instance of page classes.

  3. The utility methods which are required to be there only for a specific view or webpage should belong to that page class only.

  4. The assertion methods shouldn't be taken care by page classes, you can have methods to return boolean but don't verify them there. For example, to verify user full name you can have method to get boolean value:

     public boolean hasDisplayedUserFullName (String userFullName) {
         return driver.findElement(By.xpath("xpathExpressionUsingFullName")).isDisplayed();
     }
    
  5. If your webpage is based on iframe, prefer to have page classes for iframes too.

Advantages of Page Object Pattern:

  1. Clean separation between test code and page code
  2. In case of any change in UI of webpage, no need to change your code at multiple places. Change only in page classes.
  3. No scattered element locators.
  4. Makes code easier to understand
  5. Easy maintenance