[フレーム]

Automation

Selenium WebDriver tutorial Step by Step

You are here: Home / Advance Selenium / Page Object Model using Selenium Webdriver and Implementation

Page Object Model using Selenium Webdriver and Implementation

by 65 Comments

[画像:Firefox browser on mac using Selenium webdriver]

In this post, we are going to discuss a very important topic or concept called Page Object Model, which you have to use in your project now or in the future if you are trying to create a framework.

Many companies use Page Object Model is a design pattern to store all locators and methods in separate Java class and we can use the same class in different test cases.

I get so many questions regarding Page Object Model framework but let me make it clear that Page Object model is just a design pattern, not a framework. There are multiple design pattern available for Java-like Singleton design pattern, Structural design pattern and so on. You can read about different design patterns in Java from this link.

We will also use Page Object Model in Selenium to make our framework efficient and robust. I also have detailed video series on Hybrid Framework in Selenium on my youtube channel where we have used the same pattern. P

This is one the most important questions in interviews as well because now a day every company is trying to switch from traditional object repository to POM.

[画像:Page Object Model using Selenium Webdriver.]

What is Page Object model using Selenium Webdriver?

1- It is a design pattern, which will help you to maintain the code and avoid code duplication, which is a crucial thing in Test automation.

2- You can store all locators and respective methods in a separate class and call them within the test in. The benefit from this will be, if any changes in web element locators then you do not have to modify the test simply modify the respective page and that all.

For example, earlier id was username and if id changed to uname then you do not have to change all the tests. You can use change the id in the respective page.

3- You can create a layer between your test script and application page, which you have to automate.

4- In other words, it will behave as Object repository where all locators are saved.

"Please don’t get confused if you are using Object repository concept which is property file, then do not use the Page Object model because both will serve the same purpose. You can use the file to store other configuration "

Implementation of Page Object Model using Selenium Webdriver

If you want to implement the Page Object model then you have two choices and you can use any of it.

1 – Page Object model without PageFactory

2- Page Object Model with Pagefactory.

Personally, I am a big fan of Page Factory, which comes with Cache Lookup feature, which allows us to store frequently used locators in the cache so that performance will be faster. We will discuss both of them in this post and you can implement any of them based on your preferences.

Page Object Model using Selenium Webdriver without PageFactory.

Let’s take a very basic scenario so that you can relate to any application. Consider you have login page where username, password, and login button is present.

I will create a separate Login Page and will store three locators, and we will create methods to access them. Kindly refer below screenshot for reference.

Now I want to design a test case so that I can use the Login class, which I created and can call the methods accordingly.

This Login class can be used by all the test scripts, which you will create in future so if any changes happened in DOM then you have to update only Login Class not all the test cases.

I have created Youtube Video for the same

[フレーム]

Program for Page Object Model using Selenium Webdriver without Page factory

package com.wordpress.Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
/**
* @author Mukesh_50
* 
* 
* This class will store all the locator and methods of login page
*
*/
public class LoginPage 
{
WebDriver driver;
By username=By.id("user_login");
By password=By.xpath(".//*[@id='user_pass']");
By loginButton=By.name("wp-submit");
public LoginPage(WebDriver driver)
{
this.driver=driver;
}
public void loginToWordpress(String userid,String pass)
{
driver.findElement(username).sendKeys(userid);
driver.findElement(password).sendKeys(pass);
driver.findElement(loginButton).click();
}
public void typeUserName(String uid)
{
driver.findElement(username).sendKeys(uid);
}
public void typePassword(String pass)
{
driver.findElement(password).sendKeys(pass);
}
public void clickOnLoginButton()
{
driver.findElement(loginButton).click();
}
}

TestCase using Page Object Model using Selenium Webdriver

/**
* 
*/
package com.wordpress.Testcases;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import com.wordpress.Pages.LoginPage;
/**
* @author Mukesh_50
*
*/
public class VerifyWordpressLogin 
{
@Test
public void verifyValidLogin()
{
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://demosite.center/wordpress/wp-login.php");
LoginPage login=new LoginPage(driver);
login.clickOnLoginButton();
driver.quit();
}
}

Page Object Model using Selenium Webdriver with Page Factory

Selenium has built in class called PageFactory, which mainly serve Page Object model purpose, which allows you to store elements in cache lookup.

The only difference, which you will get without PageFactory and with PageFactory, is just initElement statement.Let us check the code and will see what changes required for with PageFactory Approach.

Another YouTube video for Page Object model with Page Factory

[フレーム]

Code for Page Object Model Using Selenium Webdriver using Page Factory

package com.wordpress.Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class LoginPageNew 
{
WebDriver driver;
public LoginPageNew(WebDriver ldriver)
{
this.driver=ldriver;
}
@FindBy(id="user_login") 
@CacheLookup
WebElement username; 
@FindBy(how=How.ID,using="user_pass")
@CacheLookup
WebElement password;
@FindBy(how=How.XPATH,using=".//*[@id='wp-submit']")
@CacheLookup
WebElement submit_button;
@FindBy(how=How.LINK_TEXT,using="Lost your password?")
@CacheLookup
WebElement forget_password_link;
public void login_wordpress(String uid,String pass)
{
username.sendKeys(uid);
password.sendKeys(pass);
submit_button.click();
}
}
 Test Case using Page Factory
package com.wordpress.Testcases;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;
import com.wordpress.Pages.LoginPage;
import com.wordpress.Pages.LoginPageNew;
import Helper.BrowserFactory;
public class VerifyValidLogin 
{
@Test
public void checkValidUser()
{
// This will launch browser and specific url 
WebDriver driver=BrowserFactory.startBrowser("firefox", "http://demosite.center/wordpress/wp-login.php");
// Created Page Object using Page Factory
LoginPageNew login_page=PageFactory.initElements(driver, LoginPageNew.class);
// Call the method
login_page.login_wordpress("admin", "demo123");
}
}

I hope you have enjoyed the article and if yes then feel free to share this article with other and let me know your feedback in below comment section.

Reader Interactions

Comments

  1. Manju says

    Hi Mukesh,

    Hope you are doing good…
    I have followed the same steps to create the POM. I am getting illegalStateException error even though used the chromedriver path correctly. I am using the chrome browser instead of firefox. please assist me where I am doing wrong.
    Chrome exe v88
    chrome v 88
    Selenium jar 3.41.59
    TestNG v7.3

  2. Shubhangi says

    Please help me understand how driver instance is passed as a constructor.I am a new bee to Java and Selenium.
    I understand that constructor is used to initialize variable to a value, we can achieve this using getters and setters.
    But unable to relate it(constructor) with WebDriver driver.
    Where in I have a different class of driver.
    Please help me with some diagram.

  3. Varsha Krishna Kumar says

    Hi mukesh ,
    A small clarification,
    In the POM eg without using page factory
    U have not called the logintowordpress(string username,string password) method from verifywordpresslogin class . Can u pls verify .
    Regards
    Varsha Krishna Kumar

  4. sonali says

    Hi Mukesh,

    How do i resolve this issue ….Element not clickable at point (1059, 232). Other element would receive the click

  5. Gaurav Arora says

    How can we apply waits in page object classes? I am applying webdriverwait and getting null pointer exception. can you take one example of clicking button and then waiting for any link to visible. I can use wait in normal framework but cannot in page object model.

  6. mahesh says

    HI Mukesh

    Please consider now we have many class for page object.
    Ex: The second page is depends on first page and the third page is depends on second page,

    In this case we want to pass driver instance for all the page object class.

    should we create object for three different class or any other way is there .

    Please explain other solution without creating object for second class.

    How to get webdriver instance form page1.?

  7. soni says

    Hi Mukesh,demo site is not working its giving below error

    demosite.center is currently unable to handle this request. HTTP ERROR 500.

    How to resolve this?

  8. pavithra says

    Kindly put geckodrive.exe file into your user folder then try it again(sometimes non admin user doesn’t gets proper privileges into Program Files folders) . Also check syntax and location of driver file is correct.

    Above as u replied me yesterday -I have save the gecko driver in User not in c driver

  9. Neelima says

    Hi Mukesh, my script has been implemented using data from excel, i too want refactor my code using POM, but facing issues, Is there any tutorial which can help me for this?,
    Else the above explanation is good enough for me when im not fetching my data from excel.
    Thanks,please do help me

  10. Daisy G says

    Hi Mukesh, Nice tutorial.Is there a way to check if entire page has been loaded including all frames in page without using webdriverwait or implicit wait. If yes how.

  11. nisha b says

    Hi Mukesh,
    Your comment is awaiting moderation.

    if i execute my selenium test whenever i found even one bug entire automation test had stopped . next test case does not get executed.
    so please tell after finding bug developer should fix the bug then only we excute test script or we just capture that bug and execute next script.
    if you try to say just capture the bug and eexcute next line script how we caputre the bug and execute next script

    • Mukesh Otwani says

      Hi Nisha,

      In this case, you can put exception catch after every action. If you catches any exception which usually happens when bug comes out(as in your case) then after this next step of execution will proceed. You need to design your framework in a way so that each action goes through exception check.

  12. Anusha says

    Hi Mukesh…Working on ur assignment .was just wondering how do i write text in paragraph…it does not work with send keys:(

  13. John says

    Hi, your article is really helpful.

    I need to read the object from excel file.

    @FindBy(how=How.XPATH,using=”.//*[@id=’wp-submit’]”)

    here, I need to get “.//*[@id=’wp-submit’]” from excel file with page factory concept. Could you please suggest some ways to do it? I tried it. its throwing some error.

  14. Gaurav Khurana says

    THis is nice explanation but would be good if you can explain the with factory code. The first program is very much clear.

    But the POM with object factory has many new syntaxes. if you add a paragraph for that it would be good. Which one is more used in industry ?

  15. skay says

    public void login_wordpress(String uid,String pass)
    {
    username.sendKeys(uid);
    password.sendKeys(pass);
    submit_button.click();
    }

    Shouldn’t the above function be like this
    public void login_wordpress(String uid,String pass)
    {
    driver.findElement(username).sendKeys(uid);
    driver.findElement(password).sendKeys(pass);
    driver.findElement(submit_button).click();
    }

  16. praneeth says

    Here it seems for every test case we are initializing and creating new object for driver. How to we maintain driver object as common for all pages and tests

  17. Sravan K Kumar says

    Dear Mukesh Otwani,
    iam creating “LoginPageNew ” like same as u ,
    and calling directly methods in another class.
    its showing null point Exception (but i am not create any “Page Factory” class)

    ” Ur class are very good ,iam following that ,
    i am not understand “Page Factory” class

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

AltStyle によって変換されたページ (->オリジナル) /