selenium-webdriver Page Object Model C#


Example

Page Objects should contain behavior, return info for assertions and possibly a method for page ready state method on initialization. Selenium supports Page Objects using annotations. In C# it's as follows:

using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;

public class WikipediaHomePage
{
    private IWebDriver driver;
    private int timeout = 10;
    private By pageLoadedElement = By.ClassName("central-featured-logo");

    [FindsBy(How = How.Id, Using = "searchInput")]
    [CacheLookup]
    private IWebElement searchInput;

    [FindsBy(How = How.CssSelector, Using = ".pure-button.pure-button-primary-progressive")]
    [CacheLookup]
    private IWebElement searchButton;

    public ResultsPage Search(string query) 
    {
        searchInput.SendKeys(query);
        searchButton.Click();
    }

    public WikipediaHomePage VerifyPageLoaded() 
    {
        new WebDriverWait(driver, TimeSpan.FromSeconds(timeout)).Until<bool>((drv) =>  return drv.ExpectedConditions.ElementExists(pageLoadedElement));

        return this;
    }
}

notes:

  • CacheLookup saves the element in the cache and saves returning a new element each call. This improves performance but isn't good for dynamically changing elements.
  • searchButton has 2 class names and no ID, that's why I can't use class name or id.
  • I verified that my locators will return me the element I want using Developer Tools (for Chrome), in other browsers you can use FireBug or similar.
  • Search() method returns another page object (ResultsPage) as the search click redirects you to another page.