How to Structure a Clean Selenium-Java Automation Framework Using Page Object Model
When you first start with automation testing, it’s easy to write all your test scripts in a single, massive file. But as your project grows, web elements change, and maintenance becomes a nightmare.
That is where the Page Object Model (POM) comes to the rescue. In this quick guide, we’ll look at how to cleanly separate your test logic from your page layout using Java and Selenium.
🚀 Why Page Object Model?
POM is a design pattern where every web page in your application has a corresponding Page Class. This class holds the element locators and the actions that can be performed on that page.
The main benefits:
- Reusability: Write a locator once, use it across multiple tests.
- Easy Maintenance: If a button ID changes, you only fix it in one place, not in twenty different test scripts.
- Readability: Your actual test files look like plain English steps.
💻 The Code Structure
Let’s look at a practical example: automating a simple login flow.
1. The Page Object Class
This class maps out the login page. It contains the web elements (locators) and the methods to interact with them.
java
package pages;
import org.openqa.selenium.By;
import org.openqa.git.WebDriver;
public class LoginPage {
private WebDriver driver;
// 1. Locate the Web Elements using private variables
private By usernameField = By.id("username");
private By passwordField = By.id("password");
private By loginButton = By.id("submit-btn");
// Constructor to initialize the driver
public LoginPage(WebDriver driver) {
this.driver = driver;
}
// 2. Action Methods
public void enterUsername(String username) {
driver.findElement(usernameField).sendKeys(username);
}
public void enterPassword(String password) {
driver.findElement(passwordField).sendKeys(password);
}
public void clickLogin() {
driver.findElement(loginButton).click();
}
}

Top comments (0)