Page Object Model (POM)

Page Object Model (POM)

Introduction

The Page Object Model (POM) is a design pattern in Selenium that helps us in creating a more readable, maintainable and reusable code.

POM is a way to organize your test code by creating a separate class file for each webpage of your application. Each class knows as Page Object , contains method that interact with the web element on the specific page.

You can write different methods and web element in Page Class . Suppose if you create Login Page Class, so you can write all the web elements and methods to perform action related to that page.

Benefits of POM

  • Readability : By separating the test logic from the page interaction, we make our code easier to understand and readable.

  • Code Maintainability : If the UI of the page changes, you only need to update the corresponding page object class, not all the test cases that uses that page.

  • Re-usability : The method in your Page Object Classes can be reused across multiple test case, reducing code duplication.

  • Separation of Concerns: POM creates a clear separation between test logic and page-specific code.

Implementing POM in Selenium with Java

Step 1: Create a Page Class

Let's create a LoginPage class to represent the login page of a web application.

package JavaSolution;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class LoginPage {
    @FindBy(xpath = "//input[@id='user-name']")
    WebElement elementForUsernameField;

    @FindBy(xpath = "//input[@id='password']")
    WebElement elementForPwdField;

    @FindBy(xpath = "//input[@id='login-button']")
    WebElement elementForLoginBtn;

    // **********************************************************

    public void setUserName(String userName){
        elementForUsernameField.sendKeys(userName);
    }

    public void setPassword(String password){
        elementForPwdField.sendKeys(password);
    }

    public void clickLogin(){
        elementForLoginBtn.click();
    }
}//class

Step 2: Create a Test Class

Now, let's create a test class to interact with the LoginPage.

package SeleniumBlogs;

import JavaSolution.LoginPage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class LoginTest {
    WebDriver  driver;
    LoginPage loginPage;

    @BeforeMethod
    public void setUps(){
        driver = new ChromeDriver();
        driver.get("https://www.saucedemo.com/");
        loginPage = new LoginPage();
    }

    @Test
    public void login(){
        loginPage.setUserName("standard_user");
        loginPage.setPassword("secret_sauce");
        loginPage.clickLogin();
    }

    @AfterMethod
    public void tearDown(){
        driver.quit();
    }
}