How to Use Page Object Model in Selenium with Java (Beginner Guide)

The Page Object Model (POM) is a popular design pattern in Selenium WebDriver that helps make test code more readable, maintainable, and reusable. In POM, each web page in your application is represented by a separate class file.


🧠 Why Use Page Object Model?

  • Code Reusability: Write the page structure once and reuse it in multiple test cases.
  • Maintenance: If UI changes, only the page class needs to be updated.
  • Readability: Tests are clean and easy to understand.

📁 Typical Project Structure

src
├── main
│   └── java
│       └── pages
│           └── LoginPage.java
│           └── DashboardPage.java
│       └── utils
│           └── BaseTest.java
├── test
│   └── java
│       └── tests
│           └── LoginTest.java

📝 Example Code

🔹 LoginPage.java

public class LoginPage {
    WebDriver driver;

    @FindBy(id = "username")
    WebElement txtUsername;

    @FindBy(id = "password")
    WebElement txtPassword;

    @FindBy(id = "loginBtn")
    WebElement btnLogin;

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

    public void login(String username, String password) {
        txtUsername.sendKeys(username);
        txtPassword.sendKeys(password);
        btnLogin.click();
    }
}

🔹 LoginTest.java

public class LoginTest extends BaseTest {
    @Test
    public void testValidLogin() {
        LoginPage login = new LoginPage(driver);
        login.login("admin", "admin123");
        Assert.assertEquals(driver.getTitle(), "Dashboard");
    }
}

🧰 Tools and Annotations Used

  • @FindBy – Used to locate web elements.
  • PageFactory.initElements() – Initializes all elements.
  • BaseTest – A reusable class to open/close the browser.

💡 Best Practices

  • Use meaningful method names like enterUsername(), clickLogin().
  • Keep tests and page classes separate.
  • Use PageFactory for cleaner element initialization.

📷 Bonus: Screenshot on Failure (Optional)

Implement a TestNG listener to capture a screenshot when a test fails. This helps in debugging.


📂 Explore the Full POM Framework on GitHub

If you'd like to see the complete implementation of the Page Object Model in a real-world Selenium project, you can visit my GitHub repository linked below.

🔗 GitHub Repository: DemoBlaze Selenium POM Framework

Feel free to ⭐️ the repository and fork it to practice!

📚 Summary

Page Object Model is essential for writing scalable and maintainable Selenium test cases. It separates logic (test) from UI structure (pages), making automation robust.


Happy Testing! 😊

Comments

Popular posts from this blog

Difference Between Smoke, Sanity & Regression Testing (With Examples)

How Selenium Works for Web Automation

Top 10 Selenium Interview Questions and Answers for QA Engineers (2025 Update)