Friday 6 June 2014

Implementing the Page Object pattern in C# using Selenium

Introduction

In my previous blog I covered implementing the Page Object pattern in C# using Microsoft Coded UI. In this blog I am going to cover implementing the Page Object pattern in C# using the Selenium Page Factory.

Page Object Pattern

There is a lot of information on the Selenium Wiki also Martin Fowler has a great blog on the subject. The following blog is a practical example of how to implement the pattern in C# using coded UI.

Application under Test

The example below is written to test the Contoso University sample web application you can follow the link to download and build the app in visual studio.

To ensure the app can be automated you will need add some Automation ID’s; the automation id is a property which helps you to find a specific UI element. There are many ways to identify UI elements but having a set ID will make things easier.

On the Nav bar you will need to add an ID for the Create Student Link



Find the Layout View (Views\Shared\ _Layout.cshtml) and add an ID.

You will need to do the same for create student view (Views\Student\Create.cshtml)


Do the same for First Name (student-firstname), Enrolment Date (student-enrolmentdate) and the create button. The create button is a HTML element see below for an example. Now build and run the app, you can use the browser development tools to verify the ID’s. 


Coding the Page Object Pattern

Let’s consider a 3 simple test case for create student, the expected outcomes are;

1. Student is created
2. User is returned to home page
3. Student is listed on homepage
The follow example focuses on test case 3. Now consider the Steps needed;

1. Open the browser
2. Select Create Student on the nav bar
3. Enter student details on the Create Student Page
4. Click Create
5. Assert the student is shown on the homepage/

The code for the test might look something like this; if you read the previous blog it will look familiar.
The homepage is defined as a new class
In the constructor we use PageFactory.InitElements to initialise the class, In a future post I will deal with adding code to verify the page is loaded. This will also initialise all the properties. The properties are defined using annotations;
In this example we are using ID’s to identify the controls.

A method is needed to click the Create Student Link and return a new page. The click handler is part of Selenium. The create student page also has a constructor that use the PageFactory.InitElements to initialise the class.

Conclusion

I have shown an example of how to create a page object pattern in c# using selenium. A full copy of the code can be download from https://github.com/sgray1/Selenium_Demo Future post will show examples on how to make test more robust.