Careeroza
Real World Example
Component Objects at a Large E-commerce Site
Large e-commerce QA teams (Flipkart, Amazon, Myntra) do not model a page as one giant class. The header, search bar, product card and cart drawer appear on many pages, so they become component objects that pages compose. A product listing page with 40 cards returns a list of ProductCard objects.
public class ProductCard {
private final WebElement root; // the .product-card element
public ProductCard(WebElement root) { this.root = root; }
public String name() { return root.findElement(By.cssSelector(".name")).getText(); }
public double price() { return Double.parseDouble(root.findElement(By.cssSelector(".price"))
.getText().replace("₹", "").replace(",", "")); }
public void addToCart() { root.findElement(By.cssSelector("button.add")).click(); }
}
public class SearchResultsPage extends BasePage {
private final By cards = By.cssSelector(".product-card");
public final HeaderComponent header;
public SearchResultsPage(WebDriver driver) {
super(driver);
header = new HeaderComponent(driver);
}
public List<ProductCard> products() {
return driver.findElements(cards).stream().map(ProductCard::new).toList();
}
}
@Test
public void cheapestHeadphonesCanBeAddedToCart() {
SearchResultsPage results = home.header.searchFor("headphones");
ProductCard cheapest = results.products().stream()
.min(Comparator.comparingDouble(ProductCard::price)).orElseThrow();
cheapest.addToCart();
Assert.assertEquals(results.header.cartCount(), "1");
}Example
mvn test -Dtest=SearchResultsTestExample output
[INFO] Running com.shopease.tests.SearchResultsTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 5.208 s [INFO] BUILD SUCCESS
What to Take Away
- Model repeated UI parts as components (header, card, drawer) and compose them into pages.
- A component is scoped to its root element, so
root.findElement(...)finds the price of this card, not the first one on the page. - Page methods return data (
List<ProductCard>, prices); the test does the sorting and asserting. - When the UI is redesigned, teams update a handful of page and component classes instead of hundreds of tests.