POM What is Page Object Model (POM)?
The Page Object Model is a design pattern that
creates an object repository for web UI elements. Each web page in the application is
represented by a separate class, which contains the elements and methods related to that
page. This helps in organizing the code better, making it more readable and maintainable.
Why Use POM? • Improved Maintainability: Changes in the UI require changes only in the
page classes, not in every test script. • Code Reusability: Common actions can be reused
across different tests, reducing code duplication. • Better Readability: Tests become more
readable as they use methods from page classes rather than direct WebDriver calls.
Implementing POM in Selenium 1. Create Page Classes: Each class corresponds to a web
page and contains locators and methods for interacting with those elements. 2. Define
Web Elements: Use locators to define the web elements on the page. 3. Implement
Methods: Create methods to perform actions like clicking buttons or entering text. 4. Use
Page Objects in Tests: In your test scripts, create instances of the page classes and call
their methods. Example Implementation Step 1: Create a Page Class Here’s an example of
a LoginPage class representing a login page: package pages; import
org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class LoginPage
{ private WebDriver driver; // Locators private By usernameField = By.id("username");
private By passwordField = By.id("password"); private By loginButton = By.id("login"); //
Constructor public LoginPage(WebDriver driver) { this.driver = driver; } // Method to enter
username public void enterUsername(String username)
{ driver.findElement(usernameField).sendKeys(username); } // Method to enter password
public void enterPassword(String password)
{ driver.findElement(passwordField).sendKeys(password); } // Method to click login button
public void clickLogin() { driver.findElement(loginButton).click(); } } Step 2: Create Test
Class In your test class, you can use the LoginPage class as follows: import
org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver;
import pages.LoginPage; public class LoginTest { public static void main(String[] args) { //
Set up WebDriver System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver(); // Navigate to login page
driver.get("http://example.com/login"); // Create an instance of LoginPage LoginPage
loginPage = new LoginPage(driver);