- October, 2020
- Share It
Page Object Model (POM) is a Design Pattern which is very popular in Selenium Test Automation. It is widely used design pattern and it can highly enhance test maintenance and reduce code duplication.
In POM web pages are represented as simple classes, and the various web elements on the page are defined as variables and used in methods. The tests then use these methods of page object classes whenever they need to interact with the UI of the certain page.
For example, we have a login page of some sort. We locate all needed elements on that page with webdriver. Then, we write methods that use that elements. So, we have all elements and all methods that we want to use in our tests in one simple class. In test class we just call the that methods with suitable arguments for certain test case.
Every page that we need to interact with, should have its own class with elements and methods (Page Object Class).
Example diagram of POM looks like this:
Why is good to use POM ?
- Code will be cleaner since by POM design pattern we should keep our tests and element locators separately. So, it will be easier to maintain code when something in the UI is changed.
- We can keep our page objects in separate repository (Page Object Repository). That will give us an opportunity to use for different purposes with different frameworks.
- Test cases will be a lot shorter since we could reuse methods from POM classes.
What is Page Factory?
Page Factory is an extension to Page Objects, primarily used for initialization of the web elements defined in the page classes (or page objects). Web elements used with Page Objects have to be initialized before they can be used further and Page Factory simplifies the initialization with the initialization method.
It looks like this:
Next thing to know about Page Factory is @FindBy annotation. Using @FindBy annotation, every WebElement variable is initialized by the Page Factory based on the locators configured to locate the element on the web page.
Examples of @FindBy:
Instead of:
The @FindBy annotation can accept lots of attributes like XPath, Id, Name, CssSelector, ClassName, LinkText, PartialLinkText, etc.
Will you use POM or not, will you use it with Page Factory extension or without?
It all depends on you, your project and your client needs. :D
From my perspective, when looking into huge dinosaur Java Selenium project without POM and PF with over 200 tests, we really need it.
A tiny UI change, will take some time to refactor code everywhere, while with POM it could be a lot shorter.
Probably a lot of you know about POM and PF, some of you are using it, I just wanted to point out importance of reusable and maintainable code in your test scripts. Especially when it gets quite big.
Author: Aleksandar Marjanović, QA Engineer @ enjoy.ing