33AutomationAutomationDesign Pattern
What is Page Object Model (POM) in test automation?
Page Object Model (POM) is a design pattern that creates an object repository for web UI elements, separating test logic from page-specific code.
Key Concepts
- Each web page is represented as a class
- Page elements are defined as variables
- User interactions are defined as methods
- Test scripts use page objects to interact with UI
Benefits of POM
- Maintainability: Changes in UI require updates in one place only
- Reusability: Page objects can be reused across multiple tests
- Readability: Tests are more readable and understandable
- Separation of Concerns: Test logic separated from page structure
- Reduced Code Duplication: Common actions defined once
Example Without POM
# Test script (not recommended)
driver.find_element(By.ID, "username").send_keys("user")
driver.find_element(By.ID, "password").send_keys("pass")
driver.find_element(By.ID, "login-btn").click()
Example With POM
# Page Object Class
class LoginPage:
def __init__(self, driver):
self.driver = driver
self.username_field = (By.ID, "username")
self.password_field = (By.ID, "password")
self.login_button = (By.ID, "login-btn")
def enter_username(self, username):
self.driver.find_element(*self.username_field).send_keys(username)
def enter_password(self, password):
self.driver.find_element(*self.password_field).send_keys(password)
def click_login(self):
self.driver.find_element(*self.login_button).click()
def login(self, username, password):
self.enter_username(username)
self.enter_password(password)
self.click_login()
# Test script (clean and maintainable)
login_page = LoginPage(driver)
login_page.login("user", "pass")
POM Best Practices
- One page object class per web page
- Keep page objects independent of tests
- Use meaningful method names
- Return page objects for method chaining
- Don’t include assertions in page objects
- Use Page Factory for initialization (in Java)