Page Object Model (POM) in Selenium
Page Object Model (POM) in Selenium
As web applications become more complex, maintaining automation test scripts can be challenging. Page Object Model (POM) is a design pattern that helps manage this complexity in Selenium test automation. It allows testers to create scalable, maintainable, and reusable test code by separating the test logic from the page structure.
What is Page Object Model?
Page Object Model is a design pattern in Selenium that creates an object repository for storing all web elements of a particular web page. Each web page of the application is represented as a separate Java class, and the elements of the page are defined as variables within that class. The actions that can be performed on these elements are implemented as methods.
This model helps in reducing code duplication and improves test maintenance, especially when there are changes in the UI.
How to Create Page Objects
Creating a Page Object in Selenium involves three basic steps:
- Create a separate Java class for each web page in the application.
- Locate the web elements on that page using locators like
@FindBy
. - Create methods in the class to perform actions on those elements.
Basic Example
Here’s a basic example:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class LoginPage {
WebDriver driver;
// Constructor
public LoginPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
// Page elements
@FindBy(id = "username")
WebElement usernameField;
@FindBy(id = "password")
WebElement passwordField;
@FindBy(id = "login")
WebElement loginButton;
// Actions
public void enterUsername(String username) {
usernameField.sendKeys(username);
}
public void enterPassword(String password) {
passwordField.sendKeys(password);
}
public void clickLogin() {
loginButton.click();
}
}
In the test class, you can now interact with the login page like this:
LoginPage login = new LoginPage(driver);
login.enterUsername("admin");
login.enterPassword("admin123");
login.clickLogin();
Advantages of Using POM
Some of the advantages of using page object model is as follows:
- Improved Code Maintenance: Any changes in the UI require changes only in the page class, not in the test scripts.
- Code Reusability: Actions and elements can be reused across multiple test cases.
- Separation of Concerns: Test logic and UI structure are separated, making the code cleaner and more understandable.
- Reduces Code Duplication: Centralized element definitions eliminate repetition.
- Better Test Readability: Test cases are easier to read and write.
By adopting the Page Object Model, you lay a strong foundation for robust and scalable Selenium test automation.