October 29, 2020

How to Use Page Object Model in Selenium (POM)

Automation
Continuous Testing

Page Object Model (POM) in Selenium is a design pattern that can be very useful for dev and test teams. Keep reading to learn how to use it for faster app testing.

What Is Page Object Model in Selenium?

Page Object Model in Selenium, also known as POM in Selenium, is a design pattern that creates an object repository for buttons, input fields, and other web elements. The main goal of using POM in Selenium is to reduce code duplication and improve the maintenance of test cases in the future. 

In a Page Object Model, consider each web page of an application as a class file. Each class file will contact the elements you find on the page. Using these elements, testers can interact with the system under test.

Let’s look at a practical example of a login page from a web application and how you would structure this using the Page Object Model in Selenium approach.

Back to top

Example of a Web Login Page Using POM in Selenium

page object model

If we look at the generated HTML, we can see the login form and the various elements contained in the page.

page object model in selenium

Here is an example of the elements to complete a login on this page that we need to work with in our test automation script. We will build a Page Object Model using this example.

The email field used as the username in this example:

<input id="email" name="email" type="text" class="form-control" placeholder="email">

The password field:

<input id="password" name="password" type="password" class="form-control" placeholder="Password">

The login button that will authenticate the provided details:

<button type="button" class="btn btn-primary" value="" name="btnLoginAuth" id="btnLoginAuth">Log In</button>

The success or error message is shown here:

<span id="spanAuthResponse" name="spanAuthResponse">Error! Invalid Auth Details provided.</span>

First, consider an example of a typical test automation script that is not using the Page Object Model.

/***
*Login Page Feature – Not using Page Object Model
*/
Public class LoginPage {

Public void TestLogin() {

        //Enter the login data
            driver.findElement(By.name("email")).sendKeys("[email protected]");
            driver.findElement(By.name("password")).sendKeys("my supersecret password");
            driver.findElement(By.name("btnLoginAuth")).click();

            //Verify error message is shown
            driver.findElement(By.name("spanAuthResponse")).isDisplayed();
            assertThat(driver.findElement(By.name("spanAuthResponse")).getText(), is("Error! Invalid Auth Details provided."));    

}

}

You may be wondering what would be the problem with this approach, as it is a very common way to get started with test automation in Selenium. However, there are two problems.

  • There is no separation between the test method and the object locators. Both are intertwined in a single method. So if the login changes, the complete test must change, which results in a lot of maintenance in the future.
  • The locators (how we find the elements) will be spread in multiple tests, so there is no easy way to update and maintain these.

Applying the Page Object Model techniques, the example above would look like this for the login page.

/**
 * Page Object for the Login page.
 */
public class LoginPage {
  protected static WebDriver driver;

  // <input name="email" type="text">
  private By usernameBy = By.name("email");
  // <input name="password" type="password">
  private By passwordBy = By.name("password");
  // <button name="btnLoginAuth" type="button">
  private By signinBy = By.name("btnLoginAuth");

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

  /**
    * Login as valid user for this application
    *
    * @param userName
    * @param password
    * @return Next Dashboard Page object
    */
  public DashboardPage loginValidUser(String userName, String password) {
    driver.findElement(usernameBy).sendKeys(userName);
    driver.findElement(passwordBy).sendKeys(password);
    driver.findElement(signinBy).click();

    return new DashboardPage(driver); //Not Yet implemented in this example
  }
}

This approach allows you to now implement the validation (test) in the following way.

/***
 * Tests login feature
 */
public class TestLogin {

  @Test
  public void testLogin() {
    LoginPage loginPage = new LoginPage(driver);
    DashboardPage dashboardPage = loginPage.loginValidUser("userName", "password"); //Not yet implemented
    assertThat(dashboardPage.getMessageText(), is("Hello userName"));
  }

}

Here are the rules that allow the desired maintainability of your test code using this approach.

  1. The page object should never make the assertions or verifications. This is part of your test and should always be in your test case, never in the page object. The page object is just the representation of the page.
  2. There is a single verification which can be in your page object and that is to verify that the page was loaded correctly. This could contain critical elements for the page to work correctly.
  3. Only add the elements you need to, keep it as clean as possible, and add to it when needed. Do not over engineer it.

Test Page Object Model with the best — start your journey with Perfecto for FREE with our 14-day trial.

Start Trial

Back to top

Scale Your Testing With Page Object Model in Selenium

The next step is to execute the test at scale. Connecting my Selenium script to a cloud provider like Perfecto allows you to scale your new Page Object Model testing quickly and easily.

page object model in selenium

Other frameworks also exist that implement this (POM) concept for both browser and mobile tests. The Quantum framework uses this approach. Here is an example using Quantum:

Here is my BDD test in plain English.

page object model

The execution of the statements in the Given, When, and Then parts are represented in code below.

page object model

As you can see the Google page is used here like we did for the login page in the Selenium example.

Back to top

Pair Page Object Model in Selenium With Perfecto

The Page Object Model is a great way to create tests that are easy to maintain and will allow you to scale your testing efforts faster, as you can reuse the object as required for any test automation flow.

Try using POM in Selenium and see how it works for your projects. For those seeking a BDD framework that works on this concept, try the Quantum framework and get more done faster.

Try Selenium With Perfecto

Perfecto integrates fully with Selenium and Quantum so you can scale your testing with ease. Perfecto’s testing cloud offers parallel execution and fast feedback via reporting. Give it a try today.

With Perfecto and Selenium, you’ll be able to:

  • Scale testing across platforms.
  • Find and fix bugs faster.
  • Integrate into your CI/CD pipeline.
  • Extend test coverage.

See for yourself why Perfecto makes testing with Selenium so much better. You can get started with a free 14-day trial of Perfecto today.

Test With Perfecto

 

Related Content

Back to top