Tuesday, April 11, 2017

Selenium WebDriver Framework Using PageFactory

Selenium WebDriver Framework Using PageFactory


Previously we saw how to create a simple Selenium WebDriver Framework. Here we will look into Selenium WebDriver Framework using PageFactory.

PageFactory can be called an enhanced model of Page Object Model. In PageFactory we use @FindBy annotation to locate the elements. @FindBy annotation is actually a way to pass a By object into a driver.findElement() call to create a WebElement. This call to driver.findElement() is completely transparent to you and will be performed in the background whenever you use the WebElement that has an annotation applied to it. Then we have the supported actions (or methods) which use the @FindBy annotations. These methods use the @FindBy instances which makes them unaffected by changes to the FindBy instances.

Steps to create a Selenium WebDriver Framework using PageFactory

1. Start by creating a new unit test project (File (menu) -> New -> Project). Enter Solution name and Location. I am using Microsoft Visual Studio Professional 2012.

2. In Solution Explorer, change the name of unit test from UnitTest1 to loginTest.

3. Write the below code in loginTest.cs file.

4. Right-click on Solution "MyTests" and add a new project of type Class Library. Name it UILibrary.

5. Change the name of Class1.cs under UILibrary to loginPage.cs.

6. Type the code (as seen in the below image) in loginPage Class in loginPage.cs file.

For PageFactory you need to use OpenQA.Selenium.Support.PageObjects namespace.

We have a constructor for LoginPage class. In the constructor we have PageFactory.InitElements Method. This method initializes the elements in the Page Object. It takes two paramenters i.e.
driver - The driver used to find elements on the page and
page - The Page Object to be populated with elements.

PageFactory.InitElements method throws an exception if a field or property decorated with the FindsByAttribute is not of type IWebElement or IList{IWebElement}.

FindsBy attribute marks program elements with methods by which to find a corresponding element on the page. Used in conjunction with the PageFactory, it allows you to quickly create Page Objects.

7. In UILibrary, add references for Selenium WebDriver and Selenium WebDriver Support.

8. Add a new CS file with name Driver.cs under UILibrary.

9. Add below code in the Driver.cs file.

10. Add reference to UILibrary for loginTests. In loginTest.cs, add namespace "using UILibrary".

10b.


Now run the EnterCredentialsForLogin() method and see the framework working.