Testing Tools

Page Object Model in Selenium: Step-by-Step Java Example

Build a clean Page Object Model with Selenium 4, Java and TestNG, from base page to fluent page methods, with code you can run today.

✍️ By QA Jobs India📅 12 Nov 2026⏱ 6 min read

The first Selenium suite most people write works fine for ten tests. By the fiftieth, the same By.id("username") appears in twelve files, and a single UI change breaks half the suite. The Page Object Model in Selenium exists to stop that from happening: each page’s locators and actions live in one class, and tests only describe what the user does.

In this guide we will build a small but realistic Page Object Model in Java with Selenium 4 and TestNG, against a public practice login page. You can copy the code, run it, and then extend the same structure for your own project. If you need a refresher on WebDriver basics first, our Selenium WebDriver tutorial covers setup.

Key takeaways

  • The Page Object Model (POM) puts locators and page actions in page classes, and keeps assertions in test classes.
  • A base page class holds shared logic like explicit waits, so page classes stay short.
  • Page methods should return the next page object, which makes tests read like user journeys.
  • PageFactory with @FindBy is optional; plain By locators with explicit waits are simpler and work well.
  • POM is the most common framework question in Selenium interviews, so be ready to explain your design choices.

What is the Page Object Model in Selenium?

The Page Object Model is a design pattern where each page (or significant component) of the application is represented by a class. The class contains:

  • Locators for elements on that page.
  • Methods for actions a user can perform, such as loginAs() or searchFor().
  • Methods that return data the test may want to check, such as an error message.

Tests then call these methods instead of using WebDriver directly. When a locator changes, you fix it in one place. When a flow changes, you update one method. The idea is described in the official Selenium documentation under design patterns and is widely used across languages and tools.

Why use POM: before and after

Without POMWith POM
Locators repeated across many testsEach locator defined once in its page class
Tests full of WebDriver callsTests read like user steps
One UI change breaks many filesOne UI change means one fix
Hard to review or onboard new testersClear structure that new joiners understand quickly
Waits scattered and inconsistentWaits handled centrally in a base page

Project setup

Create a Maven project with these dependencies. Selenium Manager, included in Selenium 4, downloads the right browser driver automatically.

<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>

A typical folder layout:

src
  main/java/pages
    BasePage.java
    LoginPage.java
    SecureAreaPage.java
  test/java/tests
    BaseTest.java
    LoginTest.java

Some teams keep pages under src/test/java as well. Either works; what matters is that pages and tests are separate packages.

Step 1: Create a base page

The base page holds the driver, a shared explicit wait and small helpers. Every page class extends it.

package pages;

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public abstract class BasePage {

    protected final WebDriver driver;
    protected final WebDriverWait wait;

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

    protected WebElement visible(By locator) {
        return wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
    }

    protected void click(By locator) {
        wait.until(ExpectedConditions.elementToBeClickable(locator)).click();
    }

    protected void type(By locator, String text) {
        WebElement element = visible(locator);
        element.clear();
        element.sendKeys(text);
    }
}

Putting waits here means no page class needs Thread.sleep, and timing behaviour stays consistent across the suite.

Step 2: Create page classes

The login page

package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class LoginPage extends BasePage {

    private static final String URL = "https://the-internet.herokuapp.com/login";

    private final By username = By.id("username");
    private final By password = By.id("password");
    private final By loginButton = By.cssSelector("button[type='submit']");
    private final By flash = By.id("flash");

    public LoginPage(WebDriver driver) {
        super(driver);
    }

    public LoginPage open() {
        driver.get(URL);
        return this;
    }

    public SecureAreaPage loginAs(String user, String pass) {
        submit(user, pass);
        return new SecureAreaPage(driver);
    }

    public LoginPage loginExpectingError(String user, String pass) {
        submit(user, pass);
        return this;
    }

    public String flashMessage() {
        return visible(flash).getText();
    }

    private void submit(String user, String pass) {
        type(username, user);
        type(password, pass);
        click(loginButton);
    }
}

Notice two login methods. loginAs returns the next page because success is expected. loginExpectingError stays on the login page. This makes the intent of each test obvious.

The secure area page

package pages;

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

public class SecureAreaPage extends BasePage {

    private final By heading = By.tagName("h2");
    private final By flash = By.id("flash");
    private final By logoutButton = By.cssSelector("a[href='/logout']");

    public SecureAreaPage(WebDriver driver) {
        super(driver);
        wait.until(ExpectedConditions.urlContains("/secure"));
    }

    public String heading() {
        return visible(heading).getText();
    }

    public String flashMessage() {
        return visible(flash).getText();
    }

    public LoginPage logout() {
        click(logoutButton);
        return new LoginPage(driver);
    }
}

The constructor waits for the URL, which acts as a simple check that navigation actually happened before the test continues.

Step 3: Write a base test and the tests

Base test with setup and teardown

package tests;

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

public abstract class BaseTest {

    protected WebDriver driver;

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

    @AfterMethod(alwaysRun = true)
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}

Tests that read like user journeys

package tests;

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

public class LoginTest extends BaseTest {

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

        Assert.assertTrue(secure.heading().contains("Secure Area"));
        Assert.assertTrue(secure.flashMessage().contains("You logged into a secure area!"));
    }

    @Test
    public void invalidUserSeesError() {
        LoginPage login = new LoginPage(driver)
                .open()
                .loginExpectingError("wronguser", "wrongpass");

        Assert.assertTrue(login.flashMessage().contains("Your username is invalid!"));
    }

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

        Assert.assertTrue(login.flashMessage().contains("You logged out of the secure area!"));
    }
}

The credentials are the public demo values shown on the practice page itself. In a real project, read them from a config file or environment variables. The tests contain no locators and no WebDriver calls beyond creating the first page. If you are new to the annotations used here, see our TestNG tutorial.

PageFactory: should you use it?

Selenium also offers PageFactory with @FindBy annotations:

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

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

It looks tidy, but it uses lazy proxies that can hide timing problems, and it does not add waits on its own. Many teams now prefer plain By fields with explicit waits, as in this guide, because behaviour is easier to reason about. In interviews, explain both and say which you chose and why.

Modelling components and dynamic elements

Real applications are not made of isolated pages. A header with search and a profile menu appears on every screen, a date picker appears in several forms, and a results table changes its rows on every search. Two techniques keep your Page Object Model in Selenium manageable as these pieces multiply.

Components through composition

Create a class for each reusable block and expose it from the pages that contain it:

package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class HeaderComponent extends BasePage {

    private final By searchBox = By.name("q");
    private final By searchButton = By.cssSelector("button.search");

    public HeaderComponent(WebDriver driver) {
        super(driver);
    }

    public void searchFor(String keyword) {
        type(searchBox, keyword);
        click(searchButton);
    }
}

A page then offers public HeaderComponent header() { return new HeaderComponent(driver); }, and a test reads homePage.header().searchFor("QA engineer"). If the header changes, one class changes.

Locators that take parameters

For lists and tables, build the locator from data instead of writing one locator per row:

private By jobTitle(String title) {
    return By.xpath("//a[contains(@class,'job-title') and normalize-space()='" + title + "']");
}

public void openJob(String title) {
    click(jobTitle(title));
}

Keep these helper methods private inside the page, so tests still speak in terms of user actions such as openJob("Senior QA Engineer").

Where test data and configuration belong

Page objects should not know which environment they are running against or which user is logging in. A clean split looks like this:

  • Config (base URL, browser, timeouts) lives in a properties or YAML file, read once at startup.
  • Test data (users, search terms, expected messages) lives in the test, a data provider or a data file.
  • Pages receive the driver and data as method arguments and never hard-code either.

This separation is what lets the same suite run on QA, staging and pre-production without code changes. It is also a common follow-up when interviewers ask how your framework handles multiple environments.

Best practices and common mistakes

Do

  • Keep assertions in tests, not in page classes. Pages return data; tests decide pass or fail.
  • Return the next page object from navigation methods.
  • Name methods after user intent: applyCoupon("SAVE10"), not clickButton3().
  • Model reusable components, like a header or date picker, as their own classes.
  • Keep the driver out of tests except for creating the first page.

Avoid

  • Giant page classes with hundreds of methods. Split by component.
  • Static WebDriver fields, which break parallel execution. Use ThreadLocal<WebDriver> when running in parallel.
  • Hiding Thread.sleep inside page methods.
  • Exposing raw WebElement objects to tests, which leaks page details into tests.

Explaining your POM in an interview

Interviewers often ask, “Walk me through your framework,” and the Page Object Model in Selenium is usually the centre of that answer. A clear structure: what the base page does, how page classes are organised, how tests get a driver, where test data and config come from, and how you handle waits and parallel runs. Then mention one thing you would improve. This topic appears in almost every list of Selenium interview questions, and it is central to the framework skills covered in our guide on how to become an SDET.

🚀 Looking for Selenium automation jobs?

QA Jobs India shares 100+ fresh QA & software testing openings every morning — manual, automation, API and remote roles.

See today’s QA jobs →

FAQs

What is the Page Object Model in Selenium?

It is a design pattern where each web page or component is represented by a class containing its locators and actions. Tests use these classes instead of calling WebDriver directly, which reduces duplication and makes maintenance easier.

What is the difference between POM and PageFactory?

POM is the design pattern. PageFactory is a Selenium helper that initialises @FindBy annotated fields in a page class. You can implement POM with or without PageFactory.

Should assertions be inside page objects?

Generally no. Page objects should perform actions and return information. Keeping assertions in tests keeps responsibilities clear and lets the same page methods support different checks.

Can the Page Object Model be used with Playwright or Cypress?

Yes. The pattern is tool-independent. Playwright’s documentation shows page object examples, and many Cypress teams use page objects or a similar pattern with custom commands.

How do I handle common elements like headers and menus?

Create component classes for them, such as HeaderComponent, and use them inside page classes through composition. This avoids duplicating header locators in every page.

Conclusion

Run the example above, then add one new page to it, such as the practice site’s checkbox or dropdown page, following the same base-page pattern. Once it feels natural, refactor one area of your real project the same way, one page at a time, and commit each step to a repository so you can show the before and after in interviews.

SIGN UP ONCE
Once you sign up, you get all this
Sign up now
  • 100+ fresh QA jobs daily + Direct HR email IDsLive every morning at 9 AM — apply straight to HR
  • Weekly Mega Job Fair800+ QA jobs from India & around the world, every week
  • Certified QA coursesUp to 3 courses included · all 17 for ₹500
  • AI ATS Resume BuilderFree resume points included
  • Full LinkedQA feedEvery post, fully unblurred
  • Complete QA Material libraryInterview Q&A, cheat sheets, templates & roadmaps

Instant activation right after payment · One login for jobs, courses, resume & LinkedQA

💎 Get every QA opening, every day

Join QA Jobs India Premium for 100+ verified QA jobs daily with HR contact details.

✓ You're subscribed — job alerts arrive daily at 9 AM
Scroll to Top