DEV Community

Cover image for Selenium Page Object Model in Java: Build a Clean Test Framework in 30 Minutes
Isha Training Solutions
Isha Training Solutions

Posted on

Selenium Page Object Model in Java: Build a Clean Test Framework in 30 Minutes

If your Selenium tests are full of repeated locators and copy-pasted code, they'll break every time the UI changes. The fix is the Page Object Model (POM), the design pattern almost every automation team (and every interviewer) expects you to know.

In this tutorial, you'll build a small but clean Selenium 4 + TestNG framework in Java using POM, with explicit waits and a reusable base test.

What is the Page Object Model?

POM means: one class per page of your application. Each page class holds:

  • the locators for that page
  • methods for the actions a user can do there (like loginAs())

Your tests then call those methods instead of touching locators directly.

Why it helps:

  • When a locator changes, you fix it in one place
  • Tests read like plain English
  • Code is reusable across many tests

What you'll need

  • Java 11 or later
  • Maven
  • Chrome browser
  • An IDE (IntelliJ IDEA or Eclipse)

We'll test the free practice site The Internet (https://the-internet.herokuapp.com/login).

Since Selenium 4.6, Selenium Manager downloads the right ChromeDriver automatically, so there's no manual driver setup.

Step 1: Add dependencies

Create a Maven project and add this to pom.xml:

<dependencies>
  <dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.25.0</version>
  </dependency>
  <dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.10.2</version>
    <scope>test</scope>
  </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Newer versions work too. Check the latest on Maven Central.

Step 2: Project structure

src/test/java/
├── pages/
│   └── LoginPage.java
└── tests/
    ├── BaseTest.java
    └── LoginTest.java
Enter fullscreen mode Exit fullscreen mode

Step 3: Create the page class

src/test/java/pages/LoginPage.java:

package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;

public class LoginPage {

    private final WebDriver driver;
    private final WebDriverWait wait;

    // Locators: kept in one place
    private final By usernameField = By.id("username");
    private final By passwordField = By.id("password");
    private final By loginButton   = By.cssSelector("button[type='submit']");
    private final By flashMessage  = By.id("flash");

    public LoginPage(WebDriver driver) {
        this.driver = driver;
        this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    }

    public LoginPage open() {
        driver.get("https://the-internet.herokuapp.com/login");
        return this;
    }

    public void loginAs(String username, String password) {
        wait.until(ExpectedConditions.visibilityOfElementLocated(usernameField))
            .sendKeys(username);
        driver.findElement(passwordField).sendKeys(password);
        driver.findElement(loginButton).click();
    }

    public String getFlashMessage() {
        return wait.until(ExpectedConditions.visibilityOfElementLocated(flashMessage))
                   .getText();
    }
}
Enter fullscreen mode Exit fullscreen mode

Notice the explicit wait (WebDriverWait). It waits for elements to appear instead of using Thread.sleep(), which makes tests faster and far less flaky.

Step 4: Create a base test

src/test/java/tests/BaseTest.java:

package tests;

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

public class BaseTest {

    protected WebDriver driver;

    @BeforeMethod
    public void setUp() {
        driver = new ChromeDriver();
        driver.manage().window().maximize();
    }

    @AfterMethod
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Every test class extends BaseTest, so browser setup and cleanup live in one place.

Step 5: Write the tests

src/test/java/tests/LoginTest.java:

package tests;

import org.testng.Assert;
import org.testng.annotations.Test;
import pages.LoginPage;

public class LoginTest extends BaseTest {

    @Test
    public void validLoginShowsSuccessMessage() {
        LoginPage loginPage = new LoginPage(driver).open();
        loginPage.loginAs("tomsmith", "SuperSecretPassword!");

        Assert.assertTrue(
            loginPage.getFlashMessage().contains("You logged into a secure area!")
        );
    }

    @Test
    public void invalidPasswordShowsError() {
        LoginPage loginPage = new LoginPage(driver).open();
        loginPage.loginAs("tomsmith", "wrongPassword");

        Assert.assertTrue(
            loginPage.getFlashMessage().contains("Your password is invalid!")
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

Look how readable the tests are: open the page, log in, check the message. No locators in sight.

Step 6: Run the tests

mvn test
Enter fullscreen mode Exit fullscreen mode

Or right-click LoginTest in your IDE and choose Run. Chrome opens, both tests run, and TestNG shows the results.

Common POM mistakes to avoid

  1. Putting assertions inside page classes. Keep checks in the test, and actions in the page.
  2. Using Thread.sleep(). Use explicit waits instead.
  3. One giant page class. Split big pages into smaller components (header, menu, forms).
  4. Hard-coding test data everywhere. Move it to a config or data file as your framework grows.

Where to go next

Once this works, level up your framework with:

  • Data-driven tests using TestNG @DataProvider
  • Config files for URLs and browsers
  • Reports with Extent Reports or Allure
  • Running in CI with Jenkins or GitHub Actions
  • Parallel execution with TestNG

I write about software testing for Isha Training Solutions. If you'd like guided, hands-on practice, we run a live Selenium automation testing with Java course covering framework design, TestNG, Jenkins and Git through real project scenarios.

Top comments (0)