Implementing Page Object Model (POM) with Selenium

The Page Object Model (POM) is a design pattern that organizes Selenium test scripts by separating web elements and test logic into different classes. This approach enhances code readability, maintainability, and reusability, making it a standard practice in test automation.

Key Components of POM

  1. Page Classes: Represent web pages and define locators and actions for that page.
  2. Test Classes: Contain the test logic and interact with the Page Classes.

Steps to Implement POM

1. Create a Page Class

A Page Class contains locators and methods to perform actions on the page.

java

Copy code
public class LoginPage {
    WebDriver driver;

    // Locators
    @FindBy(id = "username") WebElement usernameField;
    @FindBy(id = "password") WebElement passwordField;
    @FindBy(id = "loginButton") WebElement loginButton;

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

    // Actions
    public void enterUsername(String username) {
        usernameField.sendKeys(username);
    }

    public void enterPassword(String password) {
        passwordField.sendKeys(password);
    }

    public void clickLogin() {
        loginButton.click();
    }
}

2. Create a Test Class

The Test Class uses the Page Class to execute actions.

java

Copy code
public class LoginTest {
    WebDriver driver;

    @BeforeMethod
    public void setup() {
        driver = new ChromeDriver();
        driver.get("https://example.com/login");
    }

    @Test
    public void testValidLogin() {
        LoginPage loginPage = new LoginPage(driver);
        loginPage.enterUsername("testuser");
        loginPage.enterPassword("password123");
        loginPage.clickLogin();
        // Add assertions here
    }

    @AfterMethod
    public void teardown() {
        driver.quit();
    }
}

Benefits of POM

  • Code Reusability: Page Classes can be reused across multiple test cases.
  • Improved Maintenance: Updates to locators or methods are centralized in one class.
  • Readability: Test logic is separate from page element definitions.

Conclusion

Implementing the Page Object Model with Selenium helps create structured, maintainable, and scalable test frameworks. By encapsulating page details and actions, it simplifies test creation and enhances efficiency, especially in large projects.

Leave a comment

Your email address will not be published. Required fields are marked *