Page Object Model Design Pattern in Selenium Java

Rahul Rana

Posted On: April 13, 2020

view count77938 Views

Read time17 Min Read

Performing Selenium test automation is not a luxury in agile development anymore, with increasing number of features to test, the workload on testers keeps piling up. To keep up with this pace, testers need to automate their tests. But, even while automating tests, a poor implementation can lead to wasted or increased efforts.

Poor implementation can happen in cases, such as when your web application’s UI keeps changing, and you struggle to keep up with them while writing Selenium test automation scripts. For example, If you had different scripts using the same web element, whenever there is a change in the element you’d have to make the change in every script. This can not only be tedious and time-exhausting, but also takes up bandwidth, which the team could have used elsewhere.

In this Selenium Java tutorial, I’ll explain how page object model (POM) can help in better script maintenance for ever increasing UI changes for Selenium test automation in Java.

What is a Page Object Model?

What is Page Object Pattern

By Louise J Gibbs

Download Image

Page Object Model (POM) is a Selenium design pattern that stores all web elements in an object repository. It reduces code duplication and improves the maintenance of test cases. In POM, each web page of your application is treated as a class file.

So, while performing Selenium test automation, the test case uses the object of this Page class to call the various methods to perform actions on the web page. Since all the web elements related to a page are present at a common location, it becomes easy to implement Selenium Java testing routines, and update them when required.

Why Do We Need a Page Object Model For Selenium Java Testing?

We now know in this Selenium Java tutorial, as the UI of your webpage changes, so does the need of changing your Selenium test automation scripts. But, by implementing Page Object Model for Selenium Java testing, you only have to change the page objects, as all the changes needed for tests are in one location.

This makes the project more reliable as you don’t have to update your tests with any change in UI. Now, a single locator change won’t have the developer walk to through the code to fix it.

Let’s take a Selenium automation test scenario, where we look for the zipcode, ”12345” among the complete list on a webpage, then we click on it to find the city and match it to the city name, “MyCityName”.

Even with a simple test, changes to the UI are made frequently. It could be the new design or restructuring of fields and buttons. This impacts the test case as you’d have a suite of Selenium Java tests that needs updating.

Some of the problems for this type of Selenium Java test are:

  • Changes in the UI breaks multiple tests often in several places
  • Duplication of selectors both inside and across tests – no reuse

This certification demonstrates your knowledge of Selenium and Java, and your expertise at automating tests for any project.

Here’s a short glimpse of the Selenium Java 101 certification from LambdaTest:

What Are The Advantages of Page Object Model (POM)?

Using Page Object Model for Selenium Java testing, we can prevent the test code from being brittle and lessen the chances of duplicated code. It also improves readability and makes the code more interactive and easy to understand.

POM introduces a decoupling layer by separating the abstraction of the test object and the Selenium Java testing scripts. This is implemented by creating an UI object to be automated to wrap HTML elements and encapsulate interactions with the UI, which in turn takes all the WebDriver calls. So, in case of any element changes, this is the only page/class to be updated to incorporate the latest UI.

Page object model helps to give more realistic names to functions which helps to map to operation being done. This design pattern can be used with any kind of framework like keyword-driven, Data-driven, hybrid framework, etc.

How To Implement Page Object Model?

This Selenium Java tutorial will demonstrate how POM is suitable for applications with multiple pages. In the page object model structure, all the web elements present on each page are separated in a single page class file along with functions to do all possible interactions on that page and is generally known as *Page.java like LoginPage.java. Below are the important topics, you need to know before we start to write our first Selenium Java testing script:

Page Factory

In order to use POM and support it effectively in project, we use Page Factory which says, create all the element locators for the page in starting of the class and initialize all the elements in the page when page is loaded and create an object of the page itself before the web element variables can be used.

Elements of a webpage can be declared as

And can be initialized using initElements function on PageFactory as

Or in a more simpler code as

Or even in class constructor as

Understanding Web Element Locators

PageFactory uses reference to actual elements on the page to initialize the referring web element on the page class file by means of Selenium locators. These locators are identified by the use of @FindBy annotation. With this annotation, the user defines a way to look up the element like by name along with the necessary information associated with the element as per given locator.

Every time a function is called for any interaction on the web page which uses this webelement variable, the driver will first try to find the element again using PageFactory. This is very helpful in case some element might not be visible at the start of the page but after some action, then also that element is available for actions as Page Factory searches for the element again when it is called for some action. For elements which are loaded initially at the time of page load and are not changed and can be accessed via cache, Page Factory provides another annotation @CacheLookup for elements which are already there and need not be found again saving time and memory and action can be performed directly on them.

This entire definition of the WebElement variable can be replaced with

The @FindBy annotation supports a range of locator strategies that makes it easier to use as per available information about the web elements. Let us understand all these to make the project structure better.

1. ID

Id locators are used to locate unique elements in the DOM. ID locators are unique to the webelement and are the fastest method to locate any web element.

2. Name

Name locators in Selenium Java testing are used to identify webelements of a page, unlike ID locators they may not be unique to a page.

3. Class

Class Name locators in Selenium Java testing are used to identify webelements through class attributes.

Note:If more than one element has the same id/name/class then it always acts on the first search element occurrence. In such cases we need to make the locator unique or use some other locator that has a unique occurrence for the required element.

4. Link

Link selectors can only be used for hyperlinks. Pick up the link text from the page html.

5. CSS

CSS selectors can also be used when it’s difficult to access ID or name. Tagname and attributes are used to make a css element locator

Text between the starting and ending tag is called innerText.

Case 1 : tag with id input id = “email”

Case 2: tag with class input class=”btn btn-default form-post” //each space in class name is replaced by dot(.)

6. Xpath

Xpath in Selenium Java Testing is used to identify web elements on the web page using XML expressions.

GROUP-1

input placeholder=’Search’ name=’firstname’

xpath with single attribute //need to use @ before attribute name and value of attribute must be in single quote

xpath with multiple attributes

Use * on place of attribute

Use * on place of tag name

GROUP-2

Any Text

xpath with inner text

xpath with inner text (contains)

xpath with inner text (not contains)

xpath with inner text (starts-with)

GROUP-3

Multiple xpath for same element

Dynamic xpath using contains

We have talked in depth about XPath and subgroups in great detail in our blog on Xpath in Selenium.

Locators In Selenium WebDriver With Examples

Writing Our First Selenium Java Test Case using Page Object Model

Before we start writing the Selenium Automation test case, we must remember a few of unsaid rules of working with Page Object Model with Selenium Java testing to make it more effective

  • A page object file should never have assertions or any kind of related functionality. It is only meant to store web element variables and their interactions.
  • Page object for a web page, need not necessarily contain all the web elements of the page. Only meaningful and required elements are to be used.
  • For almost all scenarios, web page interactions redirects/leads to a new page. So the page should return a page object of the following page in all valid cases.
  • automation-trial-now

To write the first Selenium Automation test case, let us take the example of Gmail login flow for easy understanding.

For our Selenium Java tutorial, this test case will have

  • Pages – GmailHomePage.java and GmailLoginPage.java and GmailInboxPage.java
  • TestBase.java
  • GmailLoginTestCase.java

TestBase Class

In this class we create the object of WebDriver class and redirect to gmail login url

GmailHomePage Class

In this, we identify the web elements of Gmail Home Page and methods to interact with web elements on it.

GmailLoginPage Class

In this, we identify the web elements of Gmail Login Page and methods to interact with web elements on it.

GmailInboxPage Class

In this, we identify the web elements of Gmail Home Page and methods to interact with web elements on it.

GmailLoginTest class

In this class we define the test case and sequence of webpage interactions

The case can be executed by using any TestRunner for the code as per library used.

This would make the first test case using POM and Selenium Java Testing, where we navigate to the gmail login page, do login and verify redirection to the inbox. A better approach would be to add another class file, GmailLoginFlow.java to add the page interactions and abstract them from main test class as following:

Updated GmailLoginTest class

GmailLoginFlow class

How to Execute Page Object Model By Using LambdaTest Selenium Grid

In order to execute the same Selenium Automation test scenario over LambdaTest, TestBase class can be modified as follows to incorporate LambdaTest properties.

Selenium Grid Tutorial For Parallel Testing

Monitoring Test Results By LambdaTest Dashboard

As the setup is completed and having run a sample test, we can now move to the dashboard to explore the run results.

Login to your LambdaTest account redirects users to dashboard, which gives an overview of the whole tests and activities done so far along with available integrations.

You can see the number of tests run via automation, run using real time browser utility, concurrent sessions. date of execution and much more.

Cross Browser Testing Dashboard

Next is the Realtime Browser Testing panel. It enables users to execute tests on any browser version of choice in any OS and resolution of user choice by just simply selecting from the available list.

Visual UI Testing enabled users to run tests with screenshots taking capability on a varied set of OS and browser combinations. It also provides features to test across different UI for responsiveness depending on different screen sizes and resolutions.

Screenshot Testing on Different Screen

Responsive Testing on Different Screen

Automation section of the dashboard helps users to keep track of all the automation run triggered along with all related automation logs and analytics.

Automation Testing Dashboard

Automation logs provided by Lambdatest can be considered as the best utility provided owing to the range of different types of logs provided. Logs in the form of video, network and test run provides users with all possible information about the run and helps in facilitating debugging and troubleshooting to a large extent.

LambdaTest Test Automation Logs

Logs for any run other than the automation, like real time testing or screenshot testing or responsive one can be found under this section. This captures all associated information along with filters for better analysis and has the ability to download those reports and screenshots.

Another important use case of using LambdaTest is that it allows you to add issues or bugs at the same time when they are encountered and provides a section in the same dashboard for easier tracking of its progress on different stages.

LambdaTest Automation Issue Tracker

Also the ability to integrate with more than 30 apps for different purposes like communication, bug tracking, CI/CD, Project Management adds more to the positives of using this tool for cloud based testing.

Watch this video to learn how to create page object model patterns with live demonstrations using TestNG.

Wrapping It Up

An object repository design pattern, Page Object Model, helps to create the test code maintainable, reusable and optimised. Combined with Page Factory, It makes writing web pages easier for selenium automation by combining all web page interactions, in a separate page file. It makes the code simple and to be adapted easily for continuous changing requirements.

In our previous Selenium Java Testing tutorials, we have covered how to test login process, user signup, access form.

So, that was all for now, you should be able to create a page object model for Selenium Java testing now. In case of any doubts, feel free to reach out to us in the comment section below. If you liked this article, share it with your friends on facebook, LinkedIn or twitter. Happy Testing

Frequently Asked Questions (FAQs)

what is an object in java?

In Java, an object is a fundamental unit of a class, representing a real-world entity or concept. It encapsulates data (attributes) and behaviors (methods), allowing you to create instances with specific properties and functionalities based on the class’s blueprint.

what is the difference between a class and an object in java

In Java, a class is a blueprint or template that defines the structure and behavior of objects. An object, on the other hand, is an instance of a class, representing a tangible entity with its own state and behavior as defined by the class.

What is an object in Java example?

In Java, an object is a concrete instance of a class, embodying attributes and behaviors. For instance, consider a “Book” class; an object of this class could represent a specific book with attributes like title and author, and methods like read and display.

What is a class and object?

A class serves as a blueprint, outlining properties and behaviors. An object, an instance of a class, embodies these attributes and actions. While a class is a conceptual framework, an object is a concrete manifestation, with memory allocated upon creation.

Why is Java an object?

Java is object-oriented due to its foundation on objects and classes. These are essential for code writing in Java. The language embraces OOP concepts: inheritance, abstraction, polymorphism, and encapsulation, all rooted in its object-oriented nature.

Is an object a type in Java?

Yes, in Java, an “object” is not a primitive data type but rather an instance of a class. All classes, including the built-in Object class, can be used to create objects, making Object a fundamental type for object-oriented programming in Java.

What is array in Java?

An array in Java is a collection that stores a specific number of elements of the same data type. It has a fixed size set upon creation and cannot change afterward. Arrays are commonly used to organize and manipulate data efficiently in Java programs.

What is an object in Selenium?

In Java, an array is a data structure that holds a fixed number of elements of the same type. It provides a way to store and access multiple values using a single variable, using indices to refer to individual elements within the array.

What is a page object?

A page object is a design pattern widely used in test automation. It encapsulates the elements and functions of a web page or application screen, enhancing test maintenance and minimizing code repetition by providing an object-oriented interface for interactions with the page.

Author Profile Author Profile Author Profile

Author’s Profile

Rahul Rana

Rahul works as a Product Marketer at LambdaTest. With his rich experience in the startup world, he wants to help startups reach new heights. An avid tech blogger, he also loves to dabble in music.

Blogs: 12



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free