All You Need To Know About Page Object Model In Selenium

Last updated on Sep 11,2024 34.8K Views
A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop. A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop.

All You Need To Know About Page Object Model In Selenium

edureka.co

Maintaining 1000 lines of code in a single class file is a cumbersome task and also it increases its complexity. In order to maintain the project structure and efficient performance of the selenium scripts, it is necessary to use different pages for different tasks. To ease the access of distributing the code into different modules, the Page object model comes to the rescue. In this article on Page Object Model in Selenium, you will be learning some of the core concepts of Page object Model and Page factory with the help of an example.

You may also go through this recording of Selenium Projects of the Selenium Training by Selenium Certified Experts where you can understand the topics in a detailed manner with examples.

Page Object Model in Selenium Webdriver | Page Object Model with Page Factory

This video talks about Page object model fundamentals, Page factory and its implementation with page object model.

What is the Page Object Model?

Page Object Model is a design pattern in test automation to create an Object Repository for web UI elements. Every web page in the application should have a corresponding page class. This Page class will find the WebElements and also may contain page methods which perform operations on those WebElements.

The tests then use the methods of this page object class whenever they need to interact with the UI of that page. The benefit here is that, if the page UI changes, then the tests need not to be changed, only the code within the page object needs to be changed. After that, all the changes that support new UI are located in one place. That’s why locators and test scripts are stored separately.

Find out our Selenium Training in Top Cities/Countries

IndiaOther Cities/Countries
BangaloreUS
HyderabadUK
PuneCanada
ChennaiAustralia
MumbaiSingapore
KolkataEdinburgh

Now let’s see why do you need the Page Object Model.

Why Page Object Model?

The below-mentioned steps depict the need of Page Object Model in Selenium.

  1. Duplication of Code: Increasing automation test coverage results in unmaintainable project structure if locators are not managed properly. This usually happens because of duplication of code or mainly due to duplicated usage of locators.
  2. Less Time Consumption: The chief problem with script maintenance is that, if ten different scripts are using the same page element, with any change in that element, you need to change all ten scripts. This is time-consuming and error-prone. One of the best approaches to script maintenance is to create a separate class file which would find web elements, fill them or verify them. 
  3. Code Maintenance: In the future, if there is a change in the web element, you need to make the change in just one class file and not 10 different scripts. That is achieved with POM and it makes code reusable, readable and maintainable. For Example, In the home page of the web application, I have a menu bar which leads to different modules with different features. While performing automation testing, many test cases would be clicking through these menu buttons to execute specific tests.
  4. Reformation of Automation Test Scripts: Now assume that the User Interface is revamped and all the menu buttons are relocated to a different position in the home page.  So, this will result in automation tests to fail. Automated test cases will fail as scripts will not be able to find particular element-locators to perform an action. Now, QA Engineer needs to walk through the whole code to update locators where necessary. Reforming the element-locators in the duplicated code will consume a lot of time to only adjust locators, while this time can be consumed to increase test coverage. Here, you can save this time by using the Page Object Model in our test automation framework.

I hope you understood why do you need a page object model. Now, let’s move further and see some of the advantages of the Page Object Model in Selenium.

Advantages of the Page Object Model:

  1. According to the Page Object Model, you should keep the tests and element locators separately. This will keep the code clean and easy to understand and maintain.
  2. The Page Object approach makes automation framework in a testing programmer friendly, more durable and comprehensive.
  3. Another important advantage is our Page Object Repository is Independent of Automation Tests. If you keep a separate repository for page objects, it helps us to use this repository for different purposes with different frameworks like you will be able to integrate this repository with other tools like JUnit/NUnit/PhpUnit as well as with TestNG/Cucumber/etc.
  4. Test cases become short and optimized as you will be able to reuse page object methods in the POM
  5. POM is best applicable for the applications which contain multiple pages. Each of which has fields which can be uniquely referenced with respect to the page.

So these are a few of the advantages that make POM as unique and easy to work with for automation testers. Now, let’s dive further and understand what is Page Factory.

What is Page Factory?

Page Factory is an inbuilt Page Object Model concept for Selenium WebDriver but it is very optimized. Here, you follow the concept of separation of Page Object Repository and Test Methods.

Additionally, with the help of the PageFactory class, I will use annotations @FindBy to find WebElement.

I hope you understand Page Factory in Selenium. Now, let’s dive deeper into this article and understand how the Page Object Model works with the help of the example below.

Creating a Page Object Model with Page Factory in Selenium WebDriver

Scenario: Here, you need to enter the valid credentials in the ‘Facebook Login’ Page in order to redirect to the ‘Facebook Home‘ Page and then log out from the account.

Follow the below steps to implement the Page Object Model Design Pattern.

Step 1: Create TestBase class. Here I have created an object of WebDriver, maximize browser, implementing waits, launching URL and etc.

In the below example program, I have taken Chrome browser and set the System Property to launch Chrome browser.

package edureka.tests;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
public class TestBase {
public static WebDriver driver = null;
@BeforeSuite
public void initialize() throws IOException{
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"srctestjavadriverschromedriver.exe");
driver = new ChromeDriver();
//To maximize browser
driver.manage().window().maximize();
//Implicit wait
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//To open facebook
driver.get("https://www.facebook.com");
}
@AfterSuite
//Test cleanup
public void TeardownTest()
{
TestBase.driver.quit();
}
}

Step 2: Creating classes for each page (Eg., Facebook Login Page,  Facebook Inbox Page) to hold element locators and their methods. Usually, you can create page objects for all available pages in the AUT. For each page,youe create a separate class with a constructor. Identify all the locators and keep them in one class. It allows us to reuse the locators in multiple methods and also helps us in easy maintenance, if there is any change in the UI, you can simply change on one Page.

Here, I have created java files (FacebookLoginPage.java and FacebookInboxPage.java) for the corresponding pages (Facebook Login Page, and Facebook Inbox Page) to hold element locators and their methods.

package edureka.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class FbHomePage {
WebDriver driver;
public FbHomePage(WebDriver driver){
this.driver=driver;
}
//Using FindBy for locating elements
@FindBy(how=How.XPATH, using="//div[text 1="Settings'" language="()='Account"][/text]") WebElement profileDropdown;
@FindBy(how=How.XPATH, using="//text()[.='Log Out']/ancestor::span[1]") WebElement logoutLink;
// Defining all the user actions (Methods) that can be performed in the Facebook home page
// This method to click on Profile Dropdown
public void clickOnProfileDropdown(){
profileDropdown.click();
}
// This method to click on Logout link
public void clickOnLogoutLink(){
logoutLink.click();
}
}
package edureka.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class FbLoginPage {
WebDriver driver;
public FbLoginPage(WebDriver driver){
this.driver=driver;
}
//Using FindBy for locating elements
@FindBy(how=How.XPATH, using="//input[@type='email'][@name='email']") WebElement emailTextBox;
@FindBy(how=How.XPATH, using="//input[@type='password'][@name='pass']") WebElement passwordTextBox;
@FindBy(how=How.XPATH, using="//input[@type='submit'][@id='u_0_5']") WebElement signinButton;
// Defining all the user actions (Methods) that can be performed in the Facebook home page</span>

// This method is to set Email in the email text box
public void setEmail(String strEmail){
emailTextBox.sendKeys(strEmail);
}
// This method is to set Password in the password text box
public void setPassword(String strPassword){
passwordTextBox.sendKeys(strPassword);

// This method is to click on Login Button
public void clickOnLoginButton(){
signinButton.click();
}
}

Step 3: Here, you need to create Test (Eg., FBLoginTest) based on the above pages. As per my test scenario which was mentioned above,test scripts run as follows.

  1. Launch browser and open facebook.com
  2. Enter user credentials and do signin
  3. Verify the loggedIn user name and do logout
package edureka.tests;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;
import pages.FbHomePage;
import pages.FbLoginPage;
public class FbLoginTest extends TestBase{
@Test
public void init() throws Exception{
//driver.get("https://www.facebook.com");
FbLoginPage loginpage = PageFactory.initElements(driver, FbLoginPage.class);
loginpage.setEmail("your-username");
loginpage.setPassword("your-password");
loginpage.clickOnLoginButton();
FbHomePage homepage = PageFactory.initElements(driver, FbHomePage.class);
homepage.clickOnProfileDropdown();
homepage.verifyLoggedInUserNameText();
homepage.clickOnLogoutLink();
}
}

Finally, you need to create the testng.xml file and link to the above created test case class files.

Step 4: Creating testng.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Everjobs Suite">
<test name="Page Object Model Project">
<classes>
<class name="edureka.tests.TestBase" />
<class name="edureka.tests.FbLoginTest" />
</classes>
</test>
</suite> <!-- Suite -->

On executing this testnG.xml file on test suite, it will redirect to facebook.com webpage and enter all the credentials. It will then verify username and then logout of the account. This is how Page Object Model can be implemented with Page Factory.

With this, we come to an end of this article on Page Object Model in Selenium. I hope you understood the concepts and it added value to your knowledge.

Got a question for us? Please mention it in the comments section of Page Object Model in Selenium article and we will get back to you.

Upcoming Batches For Selenium Course
Course NameDateDetails
Selenium Course

Class Starts on 23rd November,2024

23rd November

SAT&SUN (Weekend Batch)
View Details
Selenium Course

Class Starts on 25th November,2024

25th November

MON-FRI (Weekday Batch)
View Details
Selenium Course

Class Starts on 21st December,2024

21st December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Selenium Framework Explained in 60 Minutes