Christmas Special : Upto 40% OFF! + 2 free courses  - SCHEDULE CALL

- Selenium Blogs -

Page Object Model (POM) with Page Factory in Selenium WebDriver

Selenium test cases may result in an unmaintainable project due to duplicate code and duplicate usage of locators. If some locator changes then you have to go through the whole code to adjust the locator where necessary. With the help of the Page Object Model (POM), it is possible to reduce or eliminating duplicate test code to a larger extent. POM improves readability and makes any document more interactive than usual. Most importantly, POM helps in creating tests with fewer keystrokes. The POM implementation can be achieved by separating the abstraction of test objects and test scripts. In this Selenium WebDriver Tutorial for Page object model and the page factory, you will learn the following topics:

  • What is the Page Object Model?
  • The need of Page Object Model
  • What are the Advantages of POM?
  • How to implement POM?
  • What is Page Factory?
  • Page object model vs page factory
  • Creating a page object model with page factory in Selenium WebDriver

What is the Page Object Model (POM)?

The page object model is a design pattern considered highly popular in Selenium test automation. It is generally used to design patterns in Selenium for enhancing code maintenance and reducing the duplicate codes. POM can be used by any kind of framework either modular, keyword-driven, data-driven, hybrid, etc. Page Object Model A page object is an object-oriented class that serves as an interface to the page of your application under test (AUT). The tests use methods of these page objects further when they want to interact with the UI of that particular page. The advantage is that if UI of that particular page changes, tests themselves don’t need to change, but there is a need to change the code within page object. Subsequently, all changes should support the new UI located in a single place.

The need of Page Object Model (POM)

The increased automated test coverage results in unmaintainable project structure especially when locators are not managed in the right way. It happens due to code duplication or duplicated usage of locators. For example, the home page of a web application has a Menu Bar that leads to different modules with multiple features. Multiple automation test cases are clicked through these Menu buttons to complete specific tasks. Consider that UI is revamped and Menu buttons are relocated to different positions in the Home page, it will result in automation tests to fail. You must be wondering why automation test will fail as scripts? They will get failed because automated test cases will not be able to find element-locators to perform specific actions. Now QA engineers have to update locators first where necessary before executing scripts. It will consume a lot of time in adjusting locators while the same time can be used to increase the test coverage. The time can be saved by using the Page Object Model in test automation framework. This is the reason how Page object models become popular in Selenium Web Driver.

What are the advantages of POM?

Here are the major benefits of Page Object Models, why they are so popular and recommended by QA engineers. advantages of POM

  • Code Reusability: The code reusability can be achieved by writing the code once and use it for different tests later.
  • Code Maintainability: it makes the clear difference between the test code and page specific code like locators and the layout. This approach makes the maintenance of code easy for QA engineers. Testers have to make changes to the page object classes that enhance the maintenance and reduces the code duplication.
  • Object Repository –Each page should be defined as the Java class and fields in the page are defined as the interface or members. The class further can be used to implement the interface.
  • Code Readability – POM, improves the overall readability of the code by separating page specific code with the test code.

How to implement POM?

Step 1 – Create a “New Package” file and name it as “pageObjects.” Now right click on the project and select New -> Package. You should use different packages for utilities, page objects, modular actions, test cases, test data, etc. it is recommended using this approach every time as it is easy to use and maintain.

Read: Simple and Important Guidance For You In Selenium Test Case

Step 2 – Now right click on the above-created package and select New -> Class. Create the “New Class” file and refer the name to the actual page from the test object. Here, two pages are the home page and login page.

Step 3 – Create a static method for each object on the Home page. Each method has an argument (driver) and a return value (element). How to implement POM?

  • The Driver is being passed as an Argument that makes Selenium able to locate elements on the browser.
  • An Element is returned so that relevant Action can be performed on it.
  • The Method is declared as the Public Static, and it can be called by any other method without instantiating the class.

These were the rules for Home Page, now follow the same rules for Login Page. How to implement POM? Now convert the First test case to the page object model test case as given below. How to implement POM? Now you can display all methods in the Home Page, once you type home_page in your test script and as you press the dot. You can expose all methods together and reduce the duplicate code significantly. This page object method can be called multiple time whenever necessary. It ensures better maintainable code because improvements should be made at one place only.

What is Page Factory?

Page Object Model is the way to represent an application in the test framework. For every page in the application, we create a page object to refer to that particular page. At the same time, Page factory is the way to implement page object models. It is an inbuilt concept for the Page object model but very optimized. One of the biggest benefits of Page Factory is AjaxElementLocatorFactory Class. It works on lazy loading concept, i.e. a timeout for web element is assigned to the page object class with the help of AjaxElementLocatorFactory. Hence, when an operation is performed on an element, the wait for its visibility start from that particular moment only. If the element is not found in the given time frame, then the test case execution will throw an exception.

Page Factory vs. Page Object Model

Page Object is a class that represents a web page and hold the members and functionality. Page Factory is the way to initialize web elements you want to interact within the page object when you create an instance of it. In brief, the Page Object model is an object repository pattern in the Selenium WebDriver. It makes the code more maintainable and reusable. Page Factory is an optimized form to create a repository in the POM concept. AjaxElementLocatorFactory is a lazy loading concept in Page Factory pattern to identify web element when they are used in any operation. Page Factory make Shandling of page objects easy and more optimized by following two techniques:

Read: What is Actions Class in Selenium and How to use it?
  • @FindBy annotation
  • initElements method

@FindBy annotation: It is used in Page Factory to declare web elements using different locators. You should pass the attributes that are used to locate web elements along with its value to the @FindBy annotation as a parameter then declare the element. For example: @FindBy (id="elementId") WebElement element; Here, we have used the ID attribute to locate the web element. Similarly, we can use the following locators with the @FindBy annotation. These are: className, CSS, name, XPath, tagName, linkText, partialLinkText initElements method: it is a static method of the Page Factory that is generally used in conjunction with @FindBy annotation. With the entitlements method, we can locate all web elements and instantiating the class quickly. One example code for the method is given below. initElements (WebDriver driver, java.lang.class pageObjectclass) Page Factory Pattern When we are using page objects alone, we have to instantiate the home-page objects again and again. It loses track of which instance of home page object you are currently interacting. The Page Factory concept reduces this burden on the user of page objects instantiation and interaction with them whenever necessary. In a nutshell, Page Factory implementation is based on the logic, initializes the page objects at strategic points only. For example,

  • When I want to interact with one page, if the page is NOT initialized automatically with HTML element then initialize it.
  • When I want to interact with one page, if the page is initialized automatically with HTML element then re-use the page object.

Now you know when objects should be instantiated at what time and it worth the time when there is a page factory pattern. Since we had the page object and page factory concepts, we don’t face any issue even if the code grows tremendously. You just have to make sure how to define page objects using the page factory concept for your web application.

Creating a page object model with page factory in Selenium WebDriver

Here, we will consider one Gmail application to learn the implementation of the page object model with a page factory in Selenium WebDriver.

What is the Scenario?

As soon as you add valid credentials in the Facebook Login Page, it is redirected to the Facebook Home page. Let us look at the steps to be followed for implementing the page object model using the page factory concept.

Read: Selenium WebDriver Architecture you Need to Know

Step 1 Create a test base class. Here, we implement waits, create an object of WebDriver, maximize bowser, launch URL, etc. in this example, we will focus on chrome browser and set the system property to launch the Chrome browser. The programming code for the testbase.java class is given below. What is the Scenario? Step 2 Now create classes for Facebook Login Page, Facebook Home page to hold web elements and locators. Usually, we should create page objects for all page in AUT. For every page, we create a separate class with a constructor. Now, you should identify locator and store them in one class. It increases the reusability of locators for multiple methods whenever necessary. For any code changes in the UI, it makes the code maintenance easy and makes changes to a particular page is simple. Here you should create Java files for both pages after the test base class to hold locators and their elements.

Step 3 As per the scenario, the script should work as follows:

  • Launch the Chrome browser and open Facebook.com
  • Enter the valid credentials and login to the Facebook home page.
  • Verify the credentials and log out.

In the end, you need to create one testing.xml file. The page object model always helps you to develop faster with cleaner code tests.

Final Words:

Page Objects and Page Factory make it easy to model web pages in Selenium and test them automatically. It makes the life of QA engineers and developers simpler. When done right, page object classes can be reused across the entire test suite and allows you to implement automated Selenium tests for the complete project early without making any compromise on agile development. By abstracting away user interactions in your page object model, it keeps test routines simple and light, you may adapt test suite based on changing requirement with minimum efforts. To know more, you should refer Selenium Web Driver Tutorial Guide in depth and learn the practical aspects of automation testing thoroughly.

Read: Roles And Responsibilities Of Automation Tester You Shouldn’t Miss!


fbicons FaceBook twitterTwitter lingedinLinkedIn pinterest Pinterest emailEmail

     Logo

    JanBask Training

    A dynamic, highly professional, and a global online training course provider committed to propelling the next generation of technology learners with a whole new way of training experience.


  • fb-15
  • twitter-15
  • linkedin-15

Comments

Trending Courses

Cyber Security Course

Cyber Security

  • Introduction to cybersecurity
  • Cryptography and Secure Communication 
  • Cloud Computing Architectural Framework
  • Security Architectures and Models
Cyber Security Course

Upcoming Class

12 days 04 Jan 2025

QA Course

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing
QA Course

Upcoming Class

5 days 28 Dec 2024

Salesforce Course

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL
Salesforce Course

Upcoming Class

7 days 30 Dec 2024

Business Analyst Course

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum
Business Analyst Course

Upcoming Class

4 days 27 Dec 2024

MS SQL Server Course

MS SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design
MS SQL Server Course

Upcoming Class

4 days 27 Dec 2024

Data Science Course

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning
Data Science Course

Upcoming Class

11 days 03 Jan 2025

DevOps Course

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing
DevOps Course

Upcoming Class

3 days 26 Dec 2024

Hadoop Course

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation
Hadoop Course

Upcoming Class

5 days 28 Dec 2024

Python Course

Python

  • Features of Python
  • Python Editors and IDEs
  • Data types and Variables
  • Python File Operation
Python Course

Upcoming Class

4 days 27 Dec 2024

Artificial Intelligence Course

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks
Artificial Intelligence Course

Upcoming Class

12 days 04 Jan 2025

Machine Learning Course

Machine Learning

  • Introduction to Machine Learning & Python
  • Machine Learning: Supervised Learning
  • Machine Learning: Unsupervised Learning
Machine Learning Course

Upcoming Class

4 days 27 Dec 2024

 Tableau Course

Tableau

  • Introduction to Tableau Desktop
  • Data Transformation Methods
  • Configuring tableau server
  • Integration with R & Hadoop
 Tableau Course

Upcoming Class

5 days 28 Dec 2024

Search Posts

Reset

Receive Latest Materials and Offers on Selenium Course

Interviews