Page Object Model (POM) is a design pattern that is used to maintain object repository for the web elements. All the web elements and their corresponding methods are maintained in a separate class for each web page. Hence, even a single change in the attribute of a WebElement will reflect across all the test cases wherever it is used. In this way, It makes it easy to maintain the object repository. Page Objects Model is best when used for applications that have multiple pages or states.
Advantages Of POM
Given below are a few advantages of POM:
- It is easier to maintain the code. Any User Interface changes will reflect wherever it is used in the class.
- Robust and Makes code readable (Methods have more realistic names).
- Makes the code reusable and reduces duplication of code (Object repository is independent of test cases).
- The code becomes less and optimized.
Steps To Create A POM
- Create a Class for every page in the application.
- In each Class, declare all the Web Elements as variable.
- Implement corresponding methods acting on the variables.
The design pattern can be structured using 2 layers/packages:
- Page Layer will hold the pages of the application as individual Class. Each Class will have WebElements declared as variables and the actions that are performed as methods.
- Test Layer will hold the test cases of the application and its verification part.
We will use a simple scenario in sample code:
- Open the URL of an application.
- Type the user name and password.
- Click on the Login button.
- Verify successful login message on the Home Page.
For the demo we have 2 pages:
- LoginPage: The page opens when the URL is entered and this is where we enter the data for login.
- HomePage: Page that gets displayed after a successful login.
For each page we would be interacting with:
- UserName, Password, Login button field on the LoginPage.
- A successful message in the HomePage.
Below actions are performed on WebElements:
- Type action on UserName field.
- Type action on the Password field.
- Click action on the Login button.
Two Classes are created for each page as shown below:
Steps To Create Test Cases:
- Initialize the driver and open the application.
- Create an object of the PageLayer Class(for each webpage) and pass the driver instance as a parameter.
- Using the object created, make a call to the methods in the PageLayer Class(for each webpage) to perform actions/verification.
- Repeat step 3 until all the actions are performed and then close the driver.
Page Object Model is a design concept or pattern used in the Selenium automation framework.
Naming convection of methods is user-friendly in the Page Object Model. The Code in POM is easy to understand, reusable and maintainable. In POM, if there is any change in the web element then, it is enough to make the changes in its respective class, rather than editing all the classes.
If you have any question about POM and Selenium best practices please let us know.