Page Object Model: what it is and the rules
A Page Object is a class that describes a page: only it knows the locators, and the test calls service-style methods such as loginAs. When the markup changes, one class is fixed instead of hundreds of tests. A method leading to another page returns that page's Page Object. Assertions stay in tests, except a check in the constructor that the right page is open.
Selenium · Page Object
A developer changed a button id and 140 tests turn red. How many places must be fixed?
The login button changed its id from submit to login-btn. The functionality is the same, but the locator was copied into every test that starts with a login, so a hundred and forty places must be fixed. This is the typical path of a project where tests are written "as it comes": convenient first, expensive later. A Page Object puts a layer between the test and the page, in which only one class knows about the markup. The lesson covers what this pattern is, which rules it has according to Selenium's recommendations and where it is usually broken.
How it works and why. A Page Object is a class that describes a page (or part of it): where its elements are and what can be done with it. The test speaks the language of the user (loginPage.loginAs(user, pass)), not the language of locators. The idea is simple: there should be just one place in the whole suite that knows the HTML structure of a given page. When the markup changes, one class is fixed, not hundreds of tests. The Selenium documentation puts it this way: public methods are the services the page offers, not the mechanics of clicks.
Layers of test code
Example: from copy-paste to a Page Object. The starting state:
@Test
void adminSeesDashboard() {
driver.get(BASE + "/login");
driver.findElement(By.id("email")).sendKeys("admin@example.com");
driver.findElement(By.id("password")).sendKeys("secret");
driver.findElement(By.id("submit")).click();
assertEquals("Dashboard", driver.findElement(By.tagName("h1")).getText());
}
// the same copied into 140 tests
The problem is not only duplication. The test mixes two levels of abstraction: what the user does (logs in) and how it is done (which fields, which locators). A new reader has to parse the mechanics to understand the scenario. After extraction:
public class LoginPage {
private final WebDriver driver;
private final By email = By.id("email");
private final By password = By.id("password");
private final By submit = By.cssSelector("[data-testid='login-submit']");
private final By error = By.cssSelector("[role='alert']");
public LoginPage(WebDriver driver) {
this.driver = driver;
// the only check in a Page Object: is this the right page
if (!driver.getCurrentUrl().endsWith("/login")) {
throw new IllegalStateException("Not the login page");
}
}
public DashboardPage loginAs(String user, String pass) {
fill(user, pass);
return new DashboardPage(driver);
}
public LoginPage loginExpectingError(String user, String pass) {
fill(user, pass);
return this;
}
public String errorText() {
return driver.findElement(error).getText();
}
private void fill(String user, String pass) {
driver.findElement(email).sendKeys(user);
driver.findElement(password).sendKeys(pass);
driver.findElement(submit).click();
}
}
Now the test is shorter and reads like a scenario:
@Test
void adminSeesDashboard() {
driver.get(BASE + "/login");
DashboardPage dashboard =
new LoginPage(driver).loginAs("admin@example.com", "secret");
assertEquals("Dashboard", dashboard.heading()); // assert in the test
}
@Test
void wrongPasswordShowsError() {
driver.get(BASE + "/login");
LoginPage page = new LoginPage(driver)
.loginExpectingError("admin@example.com", "bad");
assertEquals("Wrong password", page.errorText());
}
Note several decisions. The loginAs method returns DashboardPage: a method that leads to another page returns its Page Object, and the test continues with it rather than with the driver. For a successful login and a login with an expected error there are different methods, since the outcome differs (another page versus the same one): this is a recommendation of the documentation. The check in the constructor confirms the right page is open: it is an exception to the "no assertions" rule, because it does not judge behaviour but guarantees a correct state.
Rules.
- Locators and interaction details are inside the class, the test does not see them.
- Methods are page services (
loginAs,addToCart), not "click the button". - Checks (assert) live in tests, not in the Page Object. The one common exception: a check in the constructor that the right page is open.
- A Page Object does not hand out a raw
WebDriverorWebElement: otherwise locators leak into tests. - Repeated blocks (header, menu, table) are extracted into separate components (the lesson “PageFactory, components and fluent style”).
A service or mechanics
clickSubmitButton()
The method repeats mechanics: the test again builds the scenario from clicks and knows which buttons the page has.
loginAs(user, pass)
The method describes the user's intent. How many fields and clicks stand behind it is known only to the Page Object.
Limits and alternatives. A Page Object does not cure unstable locators and waits: they are fixed the same way (the lessons “Locators: By, CSS versus XPath, relative locators” and “Waits: implicit, explicit, fluent”), just in one place. Waits naturally live inside the methods: a test should not know that clickability was awaited before a click. For tiny suites of a few tests, separate classes may be excessive: with a few pages and ten tests, helper methods are enough. The cost of the pattern grows when classes become "god classes". On complex pages a different split is better: components and composition instead of one huge class per page.
Common mistakes.
- A "god" class for a whole page and methods for every button with no business meaning: it is just copy-paste moved elsewhere.
- Asserts in a Page Object: it is not visible in the test what is checked, and one class starts deciding what counts as an error.
- A method that returns
WebElement: the test writes locators and waits, and the layer loses its point. - A shared
static WebDriverin a base class: parallel threads drive someone else's browser (the lesson “Parallel runs: a driver per thread, isolation, CI”).
Check yourself
A colleague added a method assertLoggedIn() with assertEquals inside to LoginPage. Why does it go against Page Object rules and what should be done instead?
Answer
Checks belong to tests: then the test shows what exactly is verified and the Page Object stays a description of the page. Instead add a method that returns data (for example heading() or isLoggedIn()) and write the assert in the test. There is one exception: a check in the constructor that the right page is open.
Why are two methods (loginAs and loginExpectingError) better for a correct and a wrong password than one with a boolean parameter?
Answer
The outcome differs in type: a successful login leads to DashboardPage while a failed one stays on LoginPage. Two methods return different types and the compiler does not let the scenario continue wrongly. A boolean parameter forces a common return type and hides the difference.
loginAs, and when the markup changes, one class is fixed. Middle/Senior: Methods model page services and return the next Page Object, while I keep checks in the tests (the exception: a check in the constructor). I hide waits inside methods, extract repeated blocks into components and make different methods for different outcomes of one action. I pass the driver through the constructor rather than keeping it in a static.