Careeroza
Why Page Object Model
The Problem With Flat Scripts
In your first tests, locators and actions sit inside the test method. That works for five tests. With 300 tests, the ShopEase team changes the login button id from #login-btn to #sign-in and 120 tests break. You now edit 120 files.
@Test
public void addToCart() {
driver.findElement(By.id("email")).sendKeys("[email protected]"); // locator copy 1 of 120
driver.findElement(By.id("password")).sendKeys("Secret@123");
driver.findElement(By.id("login-btn")).click();
driver.findElement(By.id("search")).sendKeys("headphones" + Keys.ENTER);
driver.findElements(By.cssSelector(".product-card")).get(0).click();
driver.findElement(By.id("add-to-cart")).click();
Assert.assertEquals(driver.findElement(By.id("cart-count")).getText(), "1");
}The Idea
Page Object Model (POM) is a design pattern: every page (or big component) of the app gets one Java class. The class holds the page's locators and exposes actions as methods (login(email, password), searchFor(text)). Tests call those methods and only contain the test steps and assertions.
Test class (what to check) Page classes (how to do it) Browser
------------------------- --------------------------- -------
LoginTest.validLogin() -------> LoginPage.login(email, pwd) ------> #email, #password, #login-btn
CartTest.addToCart() -------> SearchPage.searchFor("tv") ------> #search, .product-card
-------> ProductPage.addToCart() ------> #add-to-cart, #cart-countBenefits
| Benefit | What it means for ShopEase tests |
|---|---|
| One place per locator | the login button id changes, you edit LoginPage only |
| Readable tests | loginPage.login(user) reads like a manual test case |
| Reuse | search, cart and checkout steps are shared by many tests |
| Easier reviews | test logic and page logic are reviewed separately |
| Less flakiness | waits are written once inside page methods, not in every test |
Tip: Rule of thumb: no driver.findElement inside a test class. If you see one in a code review, move it into a page class.