Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 37 ยท Page Objects and UI Tests

The Page Object Pattern

Learn the page object pattern: keep locators and browser calls out of Cucumber steps, design intention-revealing methods, return page objects, and test them with a fake driver.

Imagine a login scenario whose step definition reads driver.findElement(By.cssSelector("#user")).sendKeys(name). It works, until the designers rename the field. Then every step that touches that field breaks, in every scenario that logs in, and you hunt through twenty files. The page object pattern solves this by putting everything that knows about a page's structure in one class, and letting step definitions talk about what a user does.

This lesson explains the pattern, shows how to design the methods, and gives a runnable Java stand-in with a fake browser so you can test the idea without Selenium. The real Selenium code is read-only here because browsers cannot run on this site.

Three layers

Gherkin What the user wants.
Step definitions Glue that calls page objects.
Page objects Locators and clicks.
Browser driver Selenium or Playwright.
1 / 2

The problem without page objects

Java
@When("I log in as {string}")
public void login(String name) {
    driver.findElement(By.id("user")).sendKeys(name);
    driver.findElement(By.id("pass")).sendKeys("secret");
    driver.findElement(By.cssSelector("button[type=submit]")).click();
}

@Then("I see the dashboard")
public void dashboard() {
    assertTrue(driver.findElement(By.cssSelector("h1.dashboard-title")).isDisplayed());
}

Locators are scattered, repeated and tied to markup. The step also mixes two jobs: deciding what to do and knowing how the page is built.

A page object

A page object is an ordinary class that wraps one page, or one significant part of a page. It owns the locators and exposes methods named after user intentions.

Java
public class LoginPage {
    private final WebDriver driver;

    private final By userField   = By.id("user");
    private final By passField   = By.id("pass");
    private final By submitButton = By.cssSelector("button[type=submit]");
    private final By errorBanner = By.cssSelector("[data-testid=login-error]");

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

    public LoginPage open(String baseUrl) {
        driver.get(baseUrl + "/login");
        return this;
    }

    public DashboardPage loginAs(String user, String password) {
        driver.findElement(userField).sendKeys(user);
        driver.findElement(passField).sendKeys(password);
        driver.findElement(submitButton).click();
        return new DashboardPage(driver);     // the next page
    }

    public String errorMessage() {
        return driver.findElement(errorBanner).getText();
    }
}

And the steps become tiny:

Java
public class LoginSteps {
    private final LoginPage loginPage;
    private final ShopWorld world;

    public LoginSteps(LoginPage loginPage, ShopWorld world) {   // injected
        this.loginPage = loginPage;
        this.world = world;
    }

    @When("I log in as {string}")
    public void login(String user) {
        world.dashboard = loginPage.loginAs(user, "secret");
    }

    @Then("I see my dashboard")
    public void dashboard() {
        assertTrue(world.dashboard.isShown());
    }
}

The page objects get their driver from a shared holder created in a hook; see Selenium with Cucumber.

Design rules

  1. Methods are user intentions, not widget operations: loginAs(user, password), not typeUsername() followed by clickSubmit(). Keep a few low-level helpers private.
  2. No assertions inside page objects, with one exception many teams allow: tiny isShown() style queries that return booleans. Assertions belong in step definitions, so the page object stays reusable for both positive and negative checks.
  3. Return the next page object when navigation happens (DashboardPage), or this when you stay.
  4. Locators live in one place and prefer stable hooks: data-testid, ids, accessible roles and labels, not long XPath chains or visual classes.
  5. One responsibility. If a page object grows past a few hundred lines, split it into component objects (a header, a product card, a modal), the topic of Component objects and waits.
  6. Do not leak the driver. Steps should not call findElement. If they must, that is a missing method.

Page objects and Gherkin

A good test of the layering is the Gherkin. Compare:

GHERKIN
# Too close to the UI
When I type "mina" into the user field
And I type "secret" into the password field
And I click the submit button

# Behavior
When Mina logs in with a valid password

The page object is what lets the steps stay on the second level. The scenario never mentions fields, because the step definition and page object absorb that detail. See Declarative scenarios.

Testing the idea with a fake driver

Here is the same architecture running without a browser. FakeDriver plays the page: it holds fields and decides what a click does. The page object and steps are real code; only the driver is fake, which shows exactly where the seam is.

Java Page object with a fake driver (Java stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

If the real page changed #submit to [data-testid=login], you would edit one string in LoginPage. No step and no scenario would change.

Page Factory, and what to avoid

Selenium's PageFactory with @FindBy annotations is an older helper that creates lazy element proxies. It still works, but many teams prefer plain By fields and a find call inside methods, which is easier to read, debug and wait for. Playwright users often skip page object classes for tiny suites and use a small helper module instead; the principle of one place for locators stays the same.

Avoid a single giant BasePage that every page extends and that hides random behavior, and avoid page objects that call each other in cycles. Prefer composition.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main benefit of a page object?

    Page objects hide page structure behind intention-revealing methods, localizing the impact of UI changes.
  2. 2. Which method name best follows page object design rules?

    Methods should describe what a user does, not which widgets are touched.
  3. 3. Where do assertions usually belong?

    Keeping assertions out of page objects keeps them reusable for success and failure checks.
  4. 4. A login method navigates to the dashboard. What should it return?

    Returning the next page object makes the flow explicit and the next steps type safe.

Summary

  • A page object wraps one page or component: locators inside, intention-revealing methods outside.
  • Steps call page objects; page objects call the driver; Gherkin never mentions locators.
  • Return the next page object on navigation, keep assertions in steps, prefer stable locators.
  • Split big pages into component objects and prefer composition over deep inheritance.

Next: Selenium with Cucumber