Page Object Model Application Using Selenium WebDriver 2.0

In the world of test automation, Selenium RC and WebDriver are the de facto web UI automation tools for testers. These tools are open source and available for free to use. And many QA engineers aspire to create their private keyword and data driven test suites using these tools. In this post, we’ll present a step by step tutorial on the page object model which is a standard design pattern solving real-time problems.

Nowadays, the page object model is a new test automation buzz word. It was brought to address the multiple bottlenecks that exist in the old tools. Let’s now move to know more about the page object model.

Page Object Model Application Using Selenium WebDriver 2.0.

1- Introduction to Page Object Model.

1.1- Why Page Object Model?

There have been several problems with the traditional automation methods (as referred above).

1- Most common is the script maintenance which gets tougher with time as the test suite grows.2- Next, when some locator changes, we need to go over the whole source code to adjust locators.3- Another problem is the duplicate code which emanates from the repeated functionality.4- The latter also leads to the duplicity of locators which makes the test code inefficient.5- Finally, the unnecessary code increases the cost of maintenance for the entire project.

As said in the beginning, the Page Object Model is a design pattern that addresses all of the above issues. It allows easy test case maintenance and reduces duplicate code. It is becoming the most widely used UI automation concept across Selenium community.

Another aspect of using Page Object Model is that the big IT companies are asking questions on it during testing job interviews. So we would suggest to all budding test engineers that they should first read this tutorial. And then refer our one of the most popular post on Selenium Interview Questions and Answers.

In case you plan to prepare for a Selenium on-line skill test, then first try the Selenium WebDriver Quiz on our site to gain confidence. Both these posts receive interest from hundred of visitors on daily basis. In today’s post, we’ll help you learning the page object model with a full-blown example.

Implement Page Object Model using Selenium WebDriver.

1.2- What is Page Object Model (POM)?

1- Page Object Model is a design pattern to define container classes for web elements that behave as object repositories.2- In this model, each page has its private page object class to access UI locators.3- The Page class maps all elements of the corresponding web page as its private members. Also, it defines public methods to manage operations on these objects.4- To increase readability – it allows the method name to set as per the task they are performing. For example, we can use a method name like waitForLoginSuccess() which waits until it gets a success message for the login operation.

1.3- Advantages of Page Object Model.

1- You can segregate the UI operations from functional flows. This makes the code clean and easy to manage.2- It lets the test cases to be written independently of the object repository. So the same object repository can be re-used for a different purpose. For example, you can use the POM-based repository for functional testing with TestNG/JUnit and for acceptance testing with JBehave/Cucumber.3- Here, we have reusable page methods in the POM classes so that you can focus on the code optimization.4- You can use more sensible method names which can be easily mapped to the UI actions. For example, if you click the login button and moves to the dashboard page. Then you can give the method name as ‘gotoDashboard()’.

2- How to Implement Page Object Model?

2.1- The Use Case for the Page Object Model Application.

We’ll give you a live example of a page object model class to automate the test cases. Following is a brief summary of the use case.

1- For the demo, we’ll use a test site which is openly available for selenium testing. The demo site URL is http://book.theautomatedtester.co.uk.2- The above URL has a landing home page which lists the links for chapters ranging from 1 to 8.3- By clicking the chapter links, you can navigate to other pages.4- In this demo, we’ll automate a basic function workflow.7- We’ll be using the homepage and chapter 1-2 links to create the page objects and the test case class files.

2.2- Steps for Building the Page Object Model Application.

1- In the first step, we’ll create java files for the corresponding pages to hold element locators and their methods.

3- Finally, we’ll prepare a test case class to implement the basic workflow. This class will import the base test class and extend its functionality.

3.1- MyTest.java

3- Page Object Model – A Step by Step Example.

3.1- STEP-(1).

SUB STEP-(1.1).

HomePage.java - Page Object Class for Home Page

Java

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

39

40

41

packagecom.techbeamers.page;

importorg.openqa.selenium.WebDriver;

importorg.openqa.selenium.WebElement;

importorg.openqa.selenium.support.FindBy;

importorg.openqa.selenium.support.PageFactory;

publicclassHomePage{

privateWebDriver driver;

@FindBy(linkText="Chapter1")

WebElement chapter1;

@FindBy(linkText="Chapter2")

WebElement chapter2;

@FindBy(linkText="Chapter3")

WebElement chapter3;

publicHomePage(WebDriver driver){

this.driver=driver;

}

// Method-1.

publicChapterFirstPage clickChapterFirst(){

chapter1.click();

returnPageFactory.initElements(driver,ChapterFirstPage.class);

}

// Method-2.

publicChapterSecondPage clickChapterSecond(){

chapter2.click();

returnPageFactory.initElements(driver,ChapterSecondPage.class);

}

// Method-3.

publicvoidclickChapterThird(){

chapter3.click();

}

}

SUB STEP-(1.2).

ChapterFirstPage.java - Chapter (1) Page Object Class

Java

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

39

40

41

42

43

44

45

46

47

48

49

50

51

52

packagecom.techbeamers.page;

importorg.openqa.selenium.WebDriver;

importorg.openqa.selenium.WebElement;

importorg.openqa.selenium.support.FindBy;

importorg.openqa.selenium.support.PageFactory;

importorg.openqa.selenium.support.ui.Select;

publicclassChapterFirstPage{

privateWebDriver driver;

@FindBy(id="secondajaxbutton")

WebElement secondajax;

@FindBy(xpath="//select[@id='selecttype']")

WebElement dropdown;

@FindBy(id="verifybutton")

WebElement verifybutton;

publicChapterFirstPage(WebDriver driver){

this.driver=driver;

}

// Method-1.

publicChapterFirstPage clickSecondAjaxButton(){

secondajax.click();

returnPageFactory.initElements(driver,ChapterFirstPage.class);

}

// Method-2.

publicChapterFirstPage clickSecondAjaxButton1(Stringdata1){

System.out.println(data1);

returnPageFactory.initElements(driver,ChapterFirstPage.class);

}

// Method-3.

publicChapterFirstPage selectDropDown(Stringvalue){

newSelect(dropdown).selectByVisibleText(value);

returnPageFactory.initElements(driver,ChapterFirstPage.class);

}

// Method-4.

publicChapterFirstPage verifyButton(){

verifybutton.click();

returnPageFactory.initElements(driver,ChapterFirstPage.class);

}

}

SUB STEP-(1.3).

ChapterSecondPage.java - Chapter (2) Page Object Class

Java

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

39

40

41

42

43

44

45

46

47

packagecom.techbeamers.page;

importorg.openqa.selenium.WebDriver;

importorg.openqa.selenium.WebElement;

importorg.openqa.selenium.support.FindBy;

importorg.openqa.selenium.support.PageFactory;

publicclassChapterSecondPage{

privateWebDriver driver;

@FindBy(xpath="//input[@name='but2']")

WebElement but2;

@FindBy(xpath="//input[@id='random']")

WebElement random;

@FindBy(linkText="Index")

WebElement index;

publicChapterSecondPage(WebDriver driver){

this.driver=driver;

}

// Method-1.

publicChapterSecondPage clickRandom(){

random.click();

returnPageFactory.initElements(driver,ChapterSecondPage.class);

}

// Method-2.

publicChapterSecondPage clickbut2(){

but2.click();

returnPageFactory.initElements(driver,ChapterSecondPage.class);

}

// Method-3.

publicHomePage clickIndex(){

index.click();

returnPageFactory.initElements(driver,HomePage.class);

}

// Method-4.

publicStringgetTest(){

returnindex.getText();

}

}

From the above code snippets, you can easily understand that element locators are declared using @FindBy annotation. And corresponding methods are also defined to separate them from each other.
PageFactory class is used to create run-time object of page classes like:

Java

1

PageFactory.initElements(driver,HomePage.class);

Another important point here is that whenever any page object method results into a new page navigation, then it should return the object of the new page class. For example, when we click the <Index> link available on the <Chapter2> page, the corresponding method i.e. <clickIndex()> should return <HomePage> object.

1

PageFactory.initElements(driver,HomePage.class);

Similarly in an another example, when you click on <clickbut2()> then the same page object will return.

1

PageFactory.initElements(driver,ChapterSecondPage.class);

3.2- STEP-(2).

After creating the desired page object files, we’ll create the base class of the test scripts. Here, you can place the common functions related to the test cases. We’ve named this file as <TestBase.java>.

TestBase.java

Java

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

packagecom.techbeamers.util;

importjava.util.concurrent.TimeUnit;

importorg.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

importorg.testng.annotations.AfterSuite;

importorg.testng.annotations.BeforeSuite;

importcom.techbeamers.page.ChapterFirstPage;

importcom.techbeamers.page.ChapterSecondPage;

importcom.techbeamers.page.HomePage;

publicclassTestBase{

protectedWebDriver driver;

protectedStringbaseUrl;

protectedHomePage homePage;

protectedChapterSecondPage chapterSecond;

protectedChapterFirstPage chapterFirstPage;

// Method-1.

@BeforeSuite

publicvoidsetUp(){

baseUrl="http://book.theautomatedtester.co.uk/";

driver=newFirefoxDriver();

driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);

}

// Method-2.

@AfterSuite

publicvoidtearDown()throwsException{

driver.quit();

}

}

3.3- STEP-(3).

In the last step, we’ll learn to prepare the test script by importing the TestBase class created in the previous step. Next, you’ll have to call the corresponding methods of the page objects as would be needed to automate the basic test case workflow. Test script’s code is chipped in below that you can save as the <MyTest.java> file.

MyTest.java

Java

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

packagecom.techbeamers.scripts;

importorg.openqa.selenium.support.PageFactory;

importorg.testng.Assert;

importorg.testng.annotations.Test;

importcom.techbeamers.page.HomePage;

importcom.techbeamers.util.TestBase;

publicclassMyTestextendsTestBase{

// Test-0.

@Test

publicvoidtestPageObject()throwsException{

homePage=PageFactory.initElements(driver,HomePage.class);

driver.get(baseUrl);

chapterSecond=homePage.clickChapterSecond();

chapterSecond.clickbut2();

chapterSecond.clickRandom();

Stringdata=chapterSecond.getTest();

homePage=chapterSecond.clickIndex();

chapterFirstPage=homePage.clickChapterFirst();

chapterFirstPage.clickSecondAjaxButton();

chapterFirstPage.clickSecondAjaxButton1(data);

chapterFirstPage.selectDropDown("Selenium Core");

chapterFirstPage.verifyButton();

}

}

Footnote.

Hello, dear readers, we hope the above explanation of Page Object Model would have given you a fair idea about the topic. And now you should be able to use it in your working environments.

You must know that this is not an end to the knowledge and application of Selenium technology. There is much more to read and understand for each one of us. So, we’ll keep coming up with the new things and concepts in the time to come.

Before we leave you here, we request you to share your feedback in the comment section. You can also support us by distributing this post in your friend circle and spread the awareness about the Page Object Model.

can you please write up on data driven framework where you pass data to test cases from excel or csv files?
it should not just different set of data for same test case but it should be like different data for different test cases.

e.g. Let say we have a register user test case and for it the test data is as follows.FIELDVALUE
First Name Amit
Last Name Sharma
Email amit_email_com
Password password123
City Delhi

I am thinking of passing the excel data file path in test case and reading the contents from it but not sure how to map the Excel file cells with web elements.

I am working on similar POM framework and wanted to use assertions to verify whether my tests have passed or failed, i dont see the assertions in your tests, can you please explain how we can use assertions in this tests.

particular i have a VerifyLogin test case which calls login method, the login method login to application and return the dashboard object similar to what you have additionally i want to assert login success with some element present on the dashboard.

Thanks, you liked the article. And regarding your query on using assertions, we added a new post to demonstrate the application of TestNG assertions in POM framework. Please refer the post on this blog and let us know if it addresses your concern. All the Best.

I was looking for a good article on Page Object Model and found this one. I read this article from start to end and gained the required knowledge about it.
Thanks Harsh for such nicely written article on POM.