LambdaTest Community

Find answers, support, and inspiration from other users

Questions
LambdaTest Community
Answered

Why do we need a page object model for Selenium Java testing?

Please anyone let me know why do we need a page object model for Selenium Java testing.

Up Vote Down Vote 0 Votes
Posted 3 months ago

Answers


As the UI of your webpage changes, so does the need for changing your Selenium test automation scripts. But, by implementing the Page Object Model for Selenium Java testing, you only have to change the page objects, as all the changes needed for tests are in one location.

This makes the project more reliable as you don’t have to update your tests with any change in UI. Now, a single locator change won’t have the developer walk through the code to fix it.

Let’s take a Selenium automation test scenario, where we look for the zipcode, ”12345” among the complete list on a webpage, then we click on it to find the city and match it to the city name, “MyCityName”.

List<WebElement> zipCodes = driver.findElements(http://By.id("zipCodes")); 
for (WebElement zipCode : zipCodes) { 
 if (zipCode.getText().equals("12345")){ 
 zipCode.click(); 
 break; 
 } 
} 
WebElement city = driver.findElement(http://By.id("city")); 
assertEquals("MyCityName", city.getText()); 

Even with a simple test, changes to the UI are made frequently. It could be the new design or restructuring of fields and buttons. This impacts the test case as you’d have a suite of Selenium Java tests that needs updating.

Some of the problems for this type of Selenium Java test are:

  • Changes in the UI breaks multiple tests often in several places
  • Duplication of selectors both inside and across tests – no reuse

Advantages of the Page Object Model (POM):

Using the Page Object Model for Selenium Java testing, we can prevent the test code from being brittle and lessen the chances of duplicated code. It also improves readability and makes the code more interactive and easy to understand.

POM introduces a decoupling layer by separating the abstraction of the test object and the Selenium Java testing scripts. This is implemented by creating a UI object to be automated to wrap HTML elements and encapsulate interactions with the UI, which in turn takes all the WebDriver calls. So, in case of any element changes, this is the only page/class to be updated to incorporate the latest UI.

Page object model helps to give more realistic names to functions which helps to map to the operation being done. This design pattern can be used with any kind of framework like keyword-driven, Data-driven, hybrid framework, etc.

Up Vote Down Vote 0 Votes
Posted 3 months ago