Page Object Model and Page Factory in Selenium | BrowserStack (2024)

Page Object Model and Page Factory are tools in Selenium that are popularly used in test automation. This tutorial will demonstrate how to use Page Object Model and Page Factory in Selenium automation projects to maintain test cases easily.

What is Page Object Model in Selenium?

Page Object Model, also known as POM, is a design pattern in Selenium that creates an object repository for storing all web elements. It helps reduce code duplication and improves test case maintenance.

In Page Object Model, consider each web page of an application as a class file. Each class file will contain only corresponding web page elements. Using these elements, testers can perform operations on the website under test.

Read More: Design Patterns in Automation Framework

Advantages of Page Object Model

  • Easy Maintenance: POM is useful when there is a change in a UI element or a change in action. An example would be: a drop-down menu is changed to a radio button. In this case, POM helps to identify the page or screen to be modified. As every screen will have different Java files, this identification is necessary to make changes in the right files. This makes test cases easy to maintain and reduces errors.
  • Code Reusability: As already discussed, all screens are independent. By using POM, one can use the test code for one screen, and reuse it in another test case. There is no need to rewrite code, thus saving time and effort.
  • Readability and Reliability of Scripts: When all screens have independent java files, one can quickly identify actions performed on a particular screen by navigating through the java file. If a change must be made to a specific code section, it can be efficiently done without affecting other files.

Implementing POM in Selenium Project

As already discussed, each java class will contain a corresponding page file. This tutorial will create 2-page files.

  • BrowserStackHomePage
  • BrowserStackSignUpPage

Each of these files will contain UI elements or Objects which are present on these screens. It will also contain the operations to be performed on these elements.

Also Read: How to Build and Execute Selenium Projects

Sample Project Structure for POM

Page Object Model and Page Factory in Selenium | BrowserStack (1)

BrowserStackHomePage Java File

Page Object Model and Page Factory in Selenium | BrowserStack (2)
Explanation of Code

  • Code Line-10 to 11: Identifying elements present on BrowserStack Home Page such as header and Get Started button
  • Code Line-17 to 24: Performing actions on identified objects on BrowserStack Home Page

Code Snippet

package browserStackPages;import static org.testng.Assert.assertEquals;import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;public class BrowserStackHomePage {WebDriver driver;By Header=By.xpath("//h1");By getStarted=By.xpath("//*[@id='signupModalButton']");public BrowserStackHomePage(WebDriver driver) {this.driver=driver;}public void veryHeader() {String getheadertext=driver.findElement(Header).getText();assertEquals("App & Browser Testing Made Easy", getheadertext);}public void clickOnGetStarted() {driver.findElement(getStarted).click();}}

BrowserStackSignUpPage Java File

Page Object Model and Page Factory in Selenium | BrowserStack (3)

Explanation of Code

  • Code Line-10 to 14: Identifying elements present on BrowserStack SignUp Page such as header and Get Started button
  • Code Line-20 to 35: Performing actions on identified objects on the BrowserStack SignUp Page

Code Snippet

package browserStackPages;import static org.testng.Assert.assertEquals;import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;public class BrowserStackSignUpPage {WebDriver driver;By Header = By.xpath("//h1");By userName = By.xpath("//*[@id='user_full_name']");By businessEmail = By.xpath("//*[@id='user_email_login']");By password = By.xpath("//*[@id='user_password']");public BrowserStackSignUpPage(WebDriver driver) {this.driver = driver;}public void veryHeader() {String getheadertext = driver.findElement(Header).getText().trim();assertEquals("Create a FREE Account", getheadertext);}public void enterFullName(String arg1) {driver.findElement(userName).sendKeys(arg1);}public void enterBusinessEmail(String arg1) {driver.findElement(businessEmail).sendKeys(arg1);}public void enterPasswrod(String arg1) {driver.findElement(password).sendKeys(arg1);}}

BrowserStackSetup Java File

Page Object Model and Page Factory in Selenium | BrowserStack (4)

Explanation of Code

  • Code Line-21 to 27: Setting up browser and website to execute test scripts
  • Code Line-29 to 43: Initializing driver object to BrowserStackHomePage & BrowserStackSignUpPage and performing actions on those pages

Code Snippet

package browserStackSetup;import java.util.concurrent.TimeUnit;import org.openqa.selenium.WebDriver;import org.openqa.selenium.chrome.ChromeDriver;import org.testng.annotations.BeforeTest;import org.testng.annotations.Test;import browserStackPages.BrowserStackHomePage;import browserStackPages.BrowserStackSignUpPage;public class BrowserStackSetup {String driverPath = "C:\\geckodriver.exe";WebDriver driver;BrowserStackHomePage objBrowserStackHomePage;BrowserStackSignUpPage objBrowserStackSignUpPage;@BeforeTestpublic void setup() {System.setProperty("webdriver.chrome.driver", "C:\\BrowserStack\\chromedriver.exe");driver = new ChromeDriver();driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);driver.get("https://www.browserstack.com/");}@Test(priority = 1)public void navigate_to_homepage_click_on_getstarted() {objBrowserStackHomePage = new BrowserStackHomePage(driver);objBrowserStackHomePage.veryHeader();objBrowserStackHomePage.clickOnGetStarted();}@Test(priority = 2)public void enter_userDetails() {objBrowserStackSignUpPage = new BrowserStackSignUpPage(driver);objBrowserStackSignUpPage.veryHeader();objBrowserStackSignUpPage.enterFullName("TestUser");objBrowserStackSignUpPage.enterBusinessEmail("TestUser@gmail.com");objBrowserStackSignUpPage.enterPasswrod("TestUserPassword");}}

Run Selenium Tests

What is Page Factory in Selenium?

Page Factory is a class provided by Selenium WebDriver to support Page Object Design patterns. In Page Factory, testers use @FindBy annotation. The initElements method is used to initialize web elements.

  • @FindBy: An annotation used in Page Factory to locate and declare web elements using different locators. Below is an example of declaring an element using @FindBy
    @FindBy(id="elementId") WebElement element;

    Similarly, one can use @FindBy with different location strategies to find web elements and perform actions on them. Below are locators that can be used:

    • ClassName
    • CSS
    • Name
    • Xpath
    • TagName
    • LinkText
    • PartialLinkText
  • initElements(): initElements is a static method in Page Factory class. Using the initElements method, one can initialize all the web elements located by @FindBy annotation.
  • lazy initialization: AjaxElementLocatorFactory is a lazy load concept in Page Factory. This only identifies web elements when used in any operation or activity. The timeout of a web element can be assigned to the object class with the help of the AjaxElementLocatorFactory.

Must-Read: TestNG Annotations in Selenium Webdriver (with Examples)

Implementing Page Factory in Selenium Project

This will try to use the same project used for the POM Model. It will reuse the 2-page files and implement Page Factory.

  • BrowserStackHomePage
  • BrowserStackSignUpPage

As discussed earlier, each of these files will only contain UI elements or Objects present on these screens along with the operations to be performed on these elements.

Sample Project Structure for Page Factory

The project structure will not change as the same project is being used. As already mentioned, Page Factory supports Page Object Model design pattern.

Page Object Model and Page Factory in Selenium | BrowserStack (6)

BrowserStackHomePage Java File

Page Object Model and Page Factory in Selenium | BrowserStack (7)

Explanation of Code

  • Code Line-13 to 17: Identifying elements present on BrowserStack Home Page such as header and Get Started button using Page Factory @FindBy annotation
  • Code Line-23 to 30: Performing actions on identified objects on the BrowserStack Home Page

Code Snippet

package browserStackPages;import static org.testng.Assert.assertEquals;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.support.FindBy;import org.openqa.selenium.support.PageFactory;public class BrowserStackHomePage {WebDriver driver;@FindBy(xpath = "//h1")WebElement Header;@FindBy(xpath = "//*[@id='signupModalButton']")WebElement getStarted;public BrowserStackHomePage(WebDriver driver) {this.driver = driver;PageFactory.initElements(driver, this);}public void veryHeader() {String getheadertext = Header.getText();assertEquals("App & Browser Testing Made Easy", getheadertext);}public void clickOnGetStarted() {getStarted.click();}}

BrowserStackSignUpPage Java File

Page Object Model and Page Factory in Selenium | BrowserStack (8)

Explanation of Code

  • Code Line-14 to 24: Identifying elements on BrowserStack SignUp Page, such as the header and Get Started button, using Page Factory @FindBy annotation.
  • Code Line-26 to 46: Performing actions on identified objects on the BrowserStack SignUp Page

Talk to an Expert

Code Snippet

package browserStackPages;import static org.testng.Assert.assertEquals;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.support.FindBy;import org.openqa.selenium.support.PageFactory;public class BrowserStackSignUpPage {WebDriver driver;@FindBy(xpath = "//h1")WebElement Header;@FindBy(xpath = "//*[@id='user_full_name']")WebElement userName;@FindBy(xpath = "//*[@id='user_email_login']")WebElement businessEmail;@FindBy(xpath = "//*[@id='user_password']")WebElement password;public BrowserStackSignUpPage(WebDriver driver) {this.driver = driver;PageFactory.initElements(driver, this);}public void veryHeader() {String getheadertext = Header.getText().trim();assertEquals("Create a FREE Account", getheadertext);}public void enterFullName(String arg1) {userName.sendKeys(arg1);}public void enterBusinessEmail(String arg1) {businessEmail.sendKeys(arg1);}public void enterPasswrod(String arg1) {password.sendKeys(arg1);}}

BrowserStackSetup Java File

Page Object Model and Page Factory in Selenium | BrowserStack (9)
Explanation of Code

  • Code Line-21 to 27: Setting up of browser and website to execute our scripts
  • Code Line-29 to 43: Initializing driver objects to BrowserStackHomePage & BrowserStackSignUpPage and performing actions on those pages.

Code Snippet

package browserStackSetup;import java.util.concurrent.TimeUnit;import org.openqa.selenium.WebDriver;import org.openqa.selenium.chrome.ChromeDriver;import org.testng.annotations.BeforeTest;import org.testng.annotations.Test;import browserStackPages.BrowserStackHomePage;import browserStackPages.BrowserStackSignUpPage;public class BrowserStackSetup {String driverPath = "C:\\geckodriver.exe";WebDriver driver;BrowserStackHomePage objBrowserStackHomePage;BrowserStackSignUpPage objBrowserStackSignUpPage;@BeforeTestpublic void setup() {System.setProperty("webdriver.chrome.driver", "C:\\BrowserStack\\chromedriver.exe");driver = new ChromeDriver();driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);driver.get("https://www.browserstack.com/");}@Test(priority = 1)public void navigate_to_homepage_click_on_getstarted() {objBrowserStackHomePage = new BrowserStackHomePage(driver);objBrowserStackHomePage.veryHeader();objBrowserStackHomePage.clickOnGetStarted();}@Test(priority = 2)public void enter_userDetails() {objBrowserStackSignUpPage = new BrowserStackSignUpPage(driver);objBrowserStackSignUpPage.veryHeader();objBrowserStackSignUpPage.enterFullName("TestUser");objBrowserStackSignUpPage.enterBusinessEmail("TestUser@gmail.com");objBrowserStackSignUpPage.enterPasswrod("TestUserPassword");}}

Test Result

Page Object Model and Page Factory in Selenium | BrowserStack (10)

Try Selenium Testing on a Real Device Cloud

Difference between Page Object Model & Page Factory in Selenium

Page Object ModelPage Factory
Finding web elements using ByFinding web elements using @FindBy
POM does not provide lazy initializationPage Factory does provide lazy initialization
Page Object Model is a design patternPageFactory is a class that implements the Page Object Model design pattern.
In POM, one needs to initialize every page object individuallyIn PageFactory, all page objects are initialized by using the initElements() method

Run the code to test the workings of the Page Object Model (POM) and Page Factory. Since these are important Selenium functions, testers need to be able to use them with ease and accuracy for Selenium automation. This will help them streamline automation testing efforts and get results quicker.

Page Object Model and Page Factory in Selenium | BrowserStack (2024)
Top Articles
Own Company Stock Within Your 401(k)? That Could Mean a Tax Advantage
Wealth Accelerator Academy+ - Money Ripples
Worcester Weather Underground
Libiyi Sawsharpener
Jennifer Hart Facebook
Pitt Authorized User
Gameplay Clarkston
Craigslist - Pets for Sale or Adoption in Zeeland, MI
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
R Tiktoksweets
Marion County Wv Tax Maps
How to Store Boiled Sweets
2016 Ford Fusion Belt Diagram
Justified Official Series Trailer
Paradise leaked: An analysis of offshore data leaks
Roof Top Snipers Unblocked
Eine Band wie ein Baum
Accident On The 210 Freeway Today
Dulce
Violent Night Showtimes Near Johnstown Movieplex
Truvy Back Office Login
Ardie From Something Was Wrong Podcast
Ff14 Sage Stat Priority
Miss America Voy Board
MethStreams Live | BoxingStreams
Palmadise Rv Lot
O'reilly Auto Parts Ozark Distribution Center Stockton Photos
Gerber Federal Credit
Watchdocumentaries Gun Mayhem 2
Edward Walk In Clinic Plainfield Il
Everything You Need to Know About NLE Choppa
CVS Near Me | Somersworth, NH
Flashscore.com Live Football Scores Livescore
Heavenly Delusion Gif
Snohomish Hairmasters
Bismarck Mandan Mugshots
Mcgiftcardmall.con
Chatropolis Call Me
Courses In Touch
Rs3 Nature Spirit Quick Guide
Ucla Basketball Bruinzone
Stitch And Angel Tattoo Black And White
News & Events | Pi Recordings
R Detroit Lions
Electric Toothbrush Feature Crossword
Hampton Inn Corbin Ky Bed Bugs
sin city jili
Inside the Bestselling Medical Mystery 'Hidden Valley Road'
OSF OnCall Urgent Care treats minor illnesses and injuries
211475039
Latest Posts
Article information

Author: Manual Maggio

Last Updated:

Views: 6083

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Manual Maggio

Birthday: 1998-01-20

Address: 359 Kelvin Stream, Lake Eldonview, MT 33517-1242

Phone: +577037762465

Job: Product Hospitality Supervisor

Hobby: Gardening, Web surfing, Video gaming, Amateur radio, Flag Football, Reading, Table tennis

Introduction: My name is Manual Maggio, I am a thankful, tender, adventurous, delightful, fantastic, proud, graceful person who loves writing and wants to share my knowledge and understanding with you.