BasePage and Fluent Page Objects

A BasePage With Common Helpers

Every page needs the same helpers: wait for an element, click it, type into it. Put them in an abstract BasePage so page classes stay short and every click waits properly.

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 el = visible(locator);
        el.clear();
        el.sendKeys(text);
    }

    protected String text(By locator) {
        return visible(locator).getText();
    }
}

Fluent Page Objects

If every method returns a page object, tests read as one chain, like a sentence:

public class SearchPage extends BasePage {
    private final By searchBox = By.id("search");
    private final By cards = By.cssSelector(".product-card");

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

    public SearchPage searchFor(String text) {
        type(searchBox, text + Keys.ENTER);
        wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(cards, 0));
        return this;
    }

    public ProductPage openResult(int index) {
        driver.findElements(cards).get(index).click();
        return new ProductPage(driver);
    }
}

// in the test
String count = new LoginPage(driver).open()
        .loginAs("[email protected]", "Secret@123")
        .searchFor("headphones")
        .openResult(0)
        .addToCart()
        .cartCount();
Assert.assertEquals(count, "1");

Tip

Tip: Do not go overboard. A chain longer than 6–7 calls hides where a failure happened. Break long flows into named steps with local variables.