A Comprehensive Guide To Page Object Model In Selenium With Page Factory

Neha Vaidya
Edureka
Published in
8 min readApr 18, 2019
Page Object Model in Selenium — Edureka

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.

Below are the topics covered in this article:

  • What is the Page Object Model?
  • Why Page Object Model?
  • Advantages of the Page Object Model
  • What is Page Factory?
  • Creating a Page Object Model with Page Factory in Selenium WebDriver

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.

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 un-maintainable 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 understood what is Page Factory. Now let’s dive deeper into this article and understand the working of the Page Object Model with the help of the below example.

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 the Chrome browser and set the System Property to launch the 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")+"\\src\\test\\java\\drivers\\chromedriver.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,you have to 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.

Java file for Facebook Login Page

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") 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();
}
}

Java file for Facebook Inbox Page

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 a 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 sign-in
  3. Verify the logged in 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 a 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 the test suite, it will redirect to facebook.com webpage and enter all the credentials. It will then verify the username and then log out of the account. This is how the 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.

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Selenium.

1. Selenium Tutorial

2. Selenium WebDriver: TestNG For Test Case Management & Report Generation

3. Building A Data Driven, Keyword Driven & Hybrid Selenium Framework

4. Locators in Selenium

5. XPath Tutorial

6. Waits in Selenium

7. Setting up a Selenium Grid for distributed Selenium testing

8. Selenium Using Python

9. Cross Browser Testing Using LambdaTest

10. Cross Browser Testing Using Selenium

11. Handle Multiple Windows in Selenium

12. Selenium Projects

13. QTP vs Selenium

14. Selenium vs RPA

15. Selenium WebDriver Architecture

16. Handling Exceptions In Selenium

17. Perform Website Testing Using Cucumber & Selenium

Originally published at https://www.edureka.co on April 18, 2019.

--

--