Page Object Model (POM) and Page Factory in Selenium

Page Object Model and Page Factory in Selenium

Summarize this blog post with:

The Page Object Model (POM) in Selenium is a design pattern that keeps web element locators and page actions in separate page classes, away from your test logic. Without it, automation scripts quickly become duplicated, hard to read, and expensive to maintain whenever the UI changes. Page Factory, a class in Selenium’s support library, builds on POM by initializing page elements through the @FindBy annotation, which reduces boilerplate code.

In this article, we will walk you through some of the core concepts of the Page Object Model and Page Factory in Selenium with the help of appropriate examples.

TL;DR

  • The Page Object Model (POM) is a design pattern in which each web page or reusable UI component is represented by a class that holds its locators and actions.
  • Page Factory is a built-in Selenium class (available in Java and C#) that helps you implement POM by initializing @FindBy-annotated elements automatically.
  • In short, POM is the architectural pattern, and Page Factory is an optional, annotation-based helper to implement it.
  • You can use POM without Page Factory, whereas Page Factory is specifically meant to be used inside page or component classes.

What is the Page Object Model in Selenium?

Page Object Model (POM), often written as POM in Selenium, is a design pattern that creates an object repository for the web elements of each page. Instead of scattering locators across test scripts, you keep them in one page class per page, so a UI change needs to be fixed in only one place. This improves code reusability and test maintenance.

In POM, each web page in the application has a corresponding page class in the automation script. This Page class will identify the various WebElements of that web page and also include methods to perform testing on those WebElements. 

Note: The names of methods inside a Page class should be given to represent the task they are performing. For example, if a loader is waiting for the order to be confirmed, the POM method name can be waitForOrderConfirmation().

Why Is Page Object Model Important in Selenium?

The below-mentioned points depict what Page Object Model is the need for a Page Object Model in Selenium.

  • Code Duplication: Without proper management of locators, automation test projects can become unwieldy due to duplicated code or excessive repetition of locator usage.
  • Time Efficiency: Maintaining scripts becomes cumbersome when multiple scripts rely on the same page element. Any change in that element necessitates updates across all affected scripts, consuming valuable time and risking errors.
  • Code Maintenance: POM mitigates code maintenance challenges by centralizing element identification and interaction in separate class files. When a web element changes, updating its locator in one class file propagates the change across all associated scripts, ensuring code remains reusable, readable, and maintainable.
  • Adaptability to UI Changes: When UI elements are restructured or relocated, existing automation tests may fail due to outdated locators. Manual updates to numerous scripts can be time-intensive. However, with POM, locating and updating element locators is centralized, streamlining the process and allowing testers to focus on enhancing test coverage rather than manual adjustments.

By implementing POM, automation frameworks gain flexibility, efficiency, and resilience to UI modifications, ultimately enhancing the effectiveness of test automation efforts.

What Are the Advantages of Page Object Model in Selenium?

The advantages of using the Page Object Model in Selenium are:

  • Reusability: The same Page object class can be used in several test cases, which reduces code duplication and improves code reuse. This saves time and effort when writing new tests because the same Page object class may be used several times.
  • Easy Maintenance: The page object model improves UI test management by organizing code logically. It helps identify which page or screen needs modification when UI elements or actions change.
  • Increases test coverage: POM allows testers to create additional tests with less effort. This increases test coverage and helps to uncover more faults, resulting in software with greater quality.
  • Readability of Scripts: POM makes the test scripts more readable and understandable by separating the script files for each screen and using logical names for methods.
  • Functional encapsulation: Using POM, all probable testing operations on a page may be described and included within the same class built for each page. This enables a clear definition and defines the scope of each page’s operation.

What is Page Factory in Selenium?

Page Factory is a class in Selenium’s support library (org.openqa.selenium.support.PageFactory) that helps implement the Page Object Model. Instead of repeating driver.findElement() calls, you declare each element once with the @FindBy annotation, and PageFactory.initElements() initializes it. This reduces boilerplate code and makes page classes easier to read and maintain.

In Page Factory, testers utilize the @FindBy annotation alongside the initElements method to initialize web elements.

The @FindBy annotation accepts various attributes such as tagName, partialLinkText, name, linkText, id, CSS, className, and XPath, enabling testers to locate and interact with elements on the web page precisely.

Elements are initialized lazily: each WebElement is a proxy that is located when you first use it, and by default it is looked up again on every use. For elements that never change, add @CacheLookup to cache the lookup.

public class LoginPage {
    private WebDriver driver;

    @FindBy(id = "username")
    WebElement username;

    @FindBy(id = "password")
    WebElement password;

    public LoginPage(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }
}

What Are the Advantages of Page Factory in Selenium?

Using the Page Factory along with the Page Object Model in Selenium brings a lot of advantages.

Listed below are a few advantages of Page Factory:

  • Easy Initialization: PageFactory simplifies web element initialization by allowing the use of annotations like @FindBy directly within the page object class. These annotations specify locators (e.g., id, name, XPath), and PageFactory automatically initializes elements upon instantiation of the page object.
  • Lazy Initialization: PageFactory employs lazy initialization, meaning elements are initialized only when accessed or interacted with in the test code. This optimizes performance by avoiding unnecessary element lookup and initialization when elements are not needed.
  • Improved Code Readability: Separating web element initialization from test code enhances code readability. With Page Factory, it’s clearer to understand code intent and interactions with the web page.

How to Implement Page Object Model Using Page Factory in Selenium

Now that we know the basics of the Page Object Model and Page Factory, let’s try to implement it in a real example to open Google’s home page and search for TestGrid.

Understanding the Test Scenario

  • Open the Google Chrome browser.
  • Visit Google’s homepage “https://google.com”.
  • Write “TestGrid” in the text box.
  • Click Search.
  • Quit the browser session.

Step 1: Create Packages for the Page Object Model

In the Page Object Model with PageFactory in Selenium, it’s advisable to organize projects into recommended packages: one for the webpages and the other for the tests. For this project, we will create the two packages with the names com.testgrid.google.page and com.testgrid.google.tests. 

Example of a recommended project structure:

com.testgrid.google.page
│
├── webpages
│   ├── LoginPage.java
│   └── GoogleHomePage.java
│   └── ...
│
└── tests
    ├── LoginTests.java
    └── GoogleHomePageTests.java
    └── ...

Step 2: Create a Page Class for Web Elements and Locators

Now that we have our project structure ready, let’s create a class for the webpage (page) package. Here, we will create a class named GoogleHomePage. This is where we will write all the web element locators and methods to handle different operations. Page Object Model in Selenium Java.

package com.testgrid.google.webpages;


import org.openqa.selenium.WebDriver;  // Import WebDriver to interact with the browser.
import org.openqa.selenium.WebElement;  // Import WebElement to locate elements.
import org.openqa.selenium.support.FindBy;  // Import FindBy to locate elements.
import org.openqa.selenium.support.How;  // Import How to specify the locator strategy.
import org.openqa.selenium.support.PageFactory;  // Import PageFactory to initialize elements.


/**
* This class represents the Google Home Page.
*/
public class GoogleHomePage {


   // WebDriver reference variable.
   private WebDriver driver;


   /**
    * Constructor for the GoogleHomePage class.
    * @param driver The WebDriver instance.
    */
   public GoogleHomePage( WebDriver driver ) {
       // Assign the WebDriver instance to the 'driver' variable.
       this.driver = driver;
       // Initialize the WebElements using the PageFactory.
       PageFactory.initElements( driver, this);
   }


   // Locate the search box element using the NAME locator strategy.
   @FindBy(how = How.NAME, using = "q")
   WebElement searchBox;
  
   // Locate the submit button element using the NAME locator strategy.
   @FindBy(how = How.NAME, using = "btnK")
   WebElement submit;


   /**
    * Method to handle seach box inputs.
    */
   public void search()
   {
       searchBox.sendKeys("TestGrid");
   }


   /**
    * Method to perform submit operation.
    */
   public void submit()
   {
       // Click the submit button.
       submit.click();
   }
}

The above code represents the GoogleHomePage class, built using the Page Object Model with PageFactory in Selenium. It utilizes annotations like @FindBy to locate web elements such as the search box and submit button. The constructor initializes the WebDriver instance and elements using Page Factory. Methods like search() and submit() perform actions on the respective elements, demonstrating the page’s functionality. This structured approach enhances code maintainability and readability. Encapsulating page-specific logic, it facilitates easier test automation and maintenance. 

Step 3: Create a Test Class to Execute Test Cases

Next, we need to create the GoogleHomeTest Class. This is where we will write all the logic to open a web browser, wait for the URL to load, perform testing, and close the browser.

package com.testgrid.google.tests;


import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;


import com.testgrid.google.webpages.GoogleHomePage;

/*
This class contains the test methods for Google Home Page.
*/
public class GoogleHomeTest
{
   // Declaring the WebDriver
   static WebDriver driver;


   /*
   This method is used to set up the test environment.
   It initializes the WebDriver and opens the Google Home Page.
   */
   @BeforeTest
   public void setUp()
   {
       // Creating an instance of ChromeDriver.
       driver = new ChromeDriver();


       // Maximizing the browser window.
       driver.manage().window().maximize();


       // Navigating to the Google Home Page.
       String url = "https://www.google.com";
       driver.get(url);


       // Setting the implicit wait time.
       driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
   }


   /*
   This method contains the actual test steps.
   It creates an object of GoogleHomePage class and calls its respective methods.
   */
   @Test(priority = 0)
   public void googleSearch()
   {
       // Creating an object of GoogleHomePage class.
       GoogleHomePage gs = new GoogleHomePage(driver);


       // Calling the search method.
       gs.search();


       // Calling the submit method.
       gs.submit();
   }


   /*
   This method is used to close the browser after the test execution.
   */
   @AfterTest
   public void closing()
   {
       // Quitting the WebDriver.
       driver.quit();
   }
}

The above code demonstrates a test class, GoogleHomeTest, for testing the Google Home Page.

  • @BeforeTest method initializes the WebDriver, maximizes the browser window, navigates to the Google Home Page, and sets the implicit wait time.
  • @Test method googleSearch() performs the actual test steps. It creates an object of the GoogleHomePage class and calls its methods for searching and submitting.
  • @AfterTest method closes the browser after test execution.

This structure ensures a systematic test setup, execution, and teardown.

Page Object Model vs Page Factory in Selenium: Key Differences

Page Object Model (POM) is a design pattern, while Page Factory is a Selenium class that helps you implement that pattern using annotations. The table below compares POM with plain By locators against POM with Page Factory (@FindBy + initElements).

FeaturePage Object Model (POM)Page Factory
Core ConceptA test automation design pattern.A built-in Selenium utility class.
PurposeSeparates UI structure from test logic for better maintainability.Simplifies element initialization inside page classes.
Locator StyleTypically uses standard By locators with driver.findElement().Uses @FindBy, @FindBys, and @FindAll annotations.
InitializationElements are located on demand when methods are called.Initialized via PageFactory.initElements() using lazy proxies.
Language SupportLanguage- and framework-agnostic (Java, Python, C#, JS, etc.).Native to Selenium Java and C# bindings only.
DependencyCan be used completely on its own.Depends on POM principles to make sense in a framework.

Conclusion

In Selenium, the Page Object Model and Page Factory design patterns are used to improve test script efficiency, readability, and maintainability. Both patterns seek to isolate page elements from test code and encapsulate interactions with those components within page classes.

The Page Object Model pattern entails establishing a unique class for each page or component of the application under test. Page Factory extends the Page Object Model paradigm by using annotations to locate and initialize page items. 

Start your smart continuous testing journey today with TestGrid.

Frequently Asked Questions

What is the difference between the Page Object Model and the Page Factory in Selenium?

The Page Object Model is a design pattern in which each web page is a class containing its locators and actions. Page Factory is a Selenium class that implements POM using @FindBy annotations and initElements(), so you don’t write findElement() calls manually. POM is the pattern; Page Factory is an optional way to implement it.

Why do we use POM in Selenium?

POM separates page locators and actions from test logic. When the UI changes, you update a locator in one page class instead of in every test, which reduces code duplication and makes tests easier to read and maintain.

Can we use POM without Page Factory in Selenium?

Yes. You can implement POM with plain By locators and driver.findElement() calls, which is also easier when you need dynamic locators. Page Factory is optional and mainly reduces boilerplate.