Page Object Model with Page Factory in Selenium

In this tutorial, we will learn about Page Object Model design pattern. We will see complete details of Page Object Model Design Pattern with Page Factory in Selenium with practical examples.

  1. What is POM Design Pattern ( Page Objects Model )
  2. What is Page Factory
  3. What is the difference between POM and Page Factory
  4. Advantages of Page Objects Model Framework
  5. Creating a POM with Page Factory in Selenium WebDriver

What is Page Object Model Design Patten (POM):

Page Object Model is a Design Pattern which has become popular in Selenium Test Automation. It is widely used design pattern in Selenium for enhancing test maintenance and reducing code duplication. Page object model (POM) can be used in any kind of framework such as modular, data-driven , keyword driven, hybrid framework etc.  A page object is an object-oriented class that serves as an interface to a page of your Application Under Test(AUT). The tests then use the methods of this page object class whenever they need to interact with the User Interface (UI) of that page. The benefit is that if the UI changes for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently, all changes to support that new UI is located in one place.

What is Page Factory:

We have seen that ‘Page Object Model’ is a way of representing an application in a test framework. For every ‘page’ in the application, we create a Page Object to reference the ‘page’ whereas a ‘Page Factory’ is one way of implementing the ‘Page Object Model’.

What is the difference between Page Object Model (POM) and Page Factory:

Page Object is a class that represents a web page and hold the functionality and members.
Page Factory is a way to initialize the web elements you want to interact with within the page object when you create an instance of it.

Advantages of Page Object Model Framework:

  • Code reusability – We could achieve code reusability by writing the code once and use it in different tests.
  • Code maintainability – There is a clean separation between test code and page specific code such as locators and layout which becomes very easy to maintain code. Code changes only on Page Object Classes when a UI change occurs. It enhances test maintenance and reduces code duplication.
  • Object Repository – Each page will be defined as a java class. All the fields in the page will be defined in an interface as members. The class will then implement the interface.
  • Readability – Improves readability due to clean separation between test code and page specific code

Creating a Page Object Model with Page Factory in Selenium WebDriver:

Here I will take Gmail Application to showcase implementation of Page Object Model Design Pattern with Page Factory using Selenium with Java.

Scenario: Enter valid credentials in the ‘Facebook Login’ Page and redirects to the ‘Facebook Home‘ Page.

Must Read:  Complete Selenium WebDriver Tutorial

The structure of my project ( Maven Project ) is as follows:

Follow below steps to Implement Page Object Model Design Pattern.

Step 1: Creating TestBase class. Here we create 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.

TestBase.java (BASE CLASS)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package 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();
    }
 
}

Must Read: How To Test TestNG Tests Using Jenkins

Step 2: Creating classes for each page (Eg., Facebook Login Page,  Facebook Inbox Page) to hold element locators and their methods. Usually, we create page objects for all available pages in the AUT. For each page, we 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. It allows us to do easy maintenance, if there is any change in the UI, we can simply change on one Page.

Here, I create 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.

FBHomePage.java (Webpage 1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package 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()=’Account Settings’]”) WebElement profileDropdown;
@FindBy(how=How.XPATH, using=“//text()[.=’Log Out’]/ancestor::span[1]”) WebElement logoutLink;
@FindBy(how=How.XPATH, using=“///div[text()=’Good afternoon, SoftwareTesting!’]”) WebElement loggedInUserNameText;
        
// 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();
}
// This method to verify LoggedIn Username Text
public String verifyLoggedInUserNameText(){
String userName = loggedInUserNameText.getText();
return userName;
}
 
}

FBLoginPage.java (Webpage 2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package 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
 
        // 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: Creating Test (Eg., FBLoginTest) based on above pages. As per my test scenario which was mentioned above, 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

FBLoginTest.java (Test Case 1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package 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(” [email protected] “);
loginpage.setPassword(“raj123456”);
loginpage.clickOnLoginButton();
FbHomePage homepage = PageFactory.initElements(driver, FbHomePage.class);
homepage.clickOnProfileDropdown();
homepage.verifyLoggedInUserNameText();
homepage.clickOnLogoutLink();
}
}

Step 4: Creating testng.xml file

Must Read: Complete TestNG Tutorial

Below is the testng.xml file.

1
2
3
4
5
6
7
8
9
10
11
12
<?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=“tests.TestBase” />
<class name=“tests.FbLoginTest” />
</classes>
</test>
</suite> <! Suite >

The Page Object Model design pattern helps you develop faster, easier and cleaner tests. You can read more on Page Object Model Design Pattern on SeleniumHQ Official Site . Hope you liked reading the article. If you have any queries, do let us know in the comments section below and share it with your friends.

Must Read: Data Driven Testing Framework In Selenium

Here I have hand-picked few posts which will help you to learn some interesting stuff:

  • Explain Test Automation Framework In The Interview
  • Test Automation Framework Interview Questions
  • Selenium Interview Questions
  • TestNG Interview Questions
  • Why You Choose Software Testing As A Career
  • Manual Testing Interview Questions
  • General Interview Questions
  • SQL Interview Questions
  • Agile Interview Questions
  • Selenium Tutorial
  • TestNG Tutorial
  • Manual Testing Tutorial
  • Katalon Studio Tutorial