Exit course
Chapter 6 of 10 Intermediate 5 min read 2 quick checks Updated

Page objects in C#

On this page
  1. The form page
  2. The page it lands on
  3. The tests, rewritten

The form tests from chapter 3 know too much. They know the dropdown's name, the CSS selector of the Submit button, and the title of the page the form lands on. When the form changes, every test that touches it changes too. A page object puts that knowledge in one class per page, and the tests talk to it in the language of the page: choose an option, submit.

This chapter shows the C# shape of the pattern. The Page Object Model course covers the design questions (what belongs in a page object, components, assertions in or out) in depth.

The form page#

Create Pages/WebFormPage.cs:

using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

namespace SeleniumCourse.Pages;

public class WebFormPage(IWebDriver driver)
{
    public const string Url = "https://www.selenium.dev/selenium/web/web-form.html";

    private static readonly By TextInput = By.Id("my-text-id");
    private static readonly By Password = By.Name("my-password");
    private static readonly By Dropdown = By.Name("my-select");
    private static readonly By SubmitButton = By.CssSelector("button[type='submit']");

    public WebFormPage Open()
    {
        driver.Navigate().GoToUrl(Url);
        return this;
    }

    public WebFormPage EnterText(string text)
    {
        driver.FindElement(TextInput).SendKeys(text);
        return this;
    }

    public WebFormPage EnterPassword(string password)
    {
        driver.FindElement(Password).SendKeys(password);
        return this;
    }

    public WebFormPage Choose(string option)
    {
        new SelectElement(driver.FindElement(Dropdown)).SelectByText(option);
        return this;
    }

    public SubmittedPage Submit()
    {
        driver.FindElement(SubmitButton).Click();
        return new SubmittedPage(driver);
    }
}

Points worth copying:

  • A primary constructor (class WebFormPage(IWebDriver driver), C# 12 and later) keeps the class short. The driver is passed in; the page object never creates or quits a browser.
  • Locators are private static readonly By fields, not IWebElement fields. A By is just a description; the element is looked up fresh each time a method runs. Holding on to an IWebElement across page changes is how you get StaleElementReferenceException.
  • Methods are user actions that return a page object: the same page for actions that stay on it, so calls can be chained, and the next page for actions that navigate.

You may see older C# examples using PageFactory.InitElements and [FindsBy] attributes. Those were never part of Selenium 4; they live on in community packages such as DotNetSeleniumExtras.PageObjects.Core. The By-field style above needs no extra package and does the same job.

The page it lands on#

Create Pages/SubmittedPage.cs:

using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

namespace SeleniumCourse.Pages;

public class SubmittedPage
{
    private readonly IWebDriver driver;

    public SubmittedPage(IWebDriver driver)
    {
        this.driver = driver;
        // The constructor waits until the browser is really on this page.
        new WebDriverWait(driver, TimeSpan.FromSeconds(10))
            .Until(d => d.Title == "Web form - target page");
    }

    public string Message => driver.FindElement(By.Id("message")).Text;

    public string SubmittedValue(string field)
    {
        var query = new Uri(driver.Url).Query.TrimStart('?').Split('&');
        var pair = query.FirstOrDefault(p => p.StartsWith(field + "="));
        return pair is null ? "" : Uri.UnescapeDataString(pair[(field.Length + 1)..].Replace('+', ' '));
    }
}

The wait in the constructor is the important line. Submit() clicks and returns immediately, while the browser is still navigating. By waiting for the target page's title before handing back the object, every test that uses SubmittedPage gets the wait for free and cannot read the old page by accident. SubmittedValue decodes the form value from the URL's query string, turning Selenium+C%23 back into Selenium C#.

A page object stores IWebElement saveButton as a field, found in its constructor. After the page re-renders, saveButton.Click() throws StaleElementReferenceException. What is the better design?

An IWebElement points at one specific DOM node; when the page replaces it, the reference goes stale. A By is only a description, so looking it up when needed always finds the current node. Retrying hides the design problem, and recreating the object everywhere moves it into the tests.

The tests, rewritten#

Tests/WebFormTests.cs now reads like a description of the behaviour:

using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using SeleniumCourse.Pages;
using SeleniumCourse.Support;

namespace SeleniumCourse.Tests;

[TestFixture]
[Category("form")]
public class WebFormTests : BaseTest
{
    private WebFormPage form = null!;

    [SetUp]
    public void OpenForm()
    {
        form = new WebFormPage(Driver).Open();
    }

    [TestCase("One", "1")]
    [TestCase("Two", "2")]
    [TestCase("Three", "3")]
    public void DropdownSelectionIsSubmitted(string label, string value)
    {
        SubmittedPage result = form.Choose(label).Submit();

        Assert.That(result.SubmittedValue("my-select"), Is.EqualTo(value));
    }

    [Test]
    public void TextAndPasswordAreSubmitted()
    {
        SubmittedPage result = form
            .EnterText("Selenium C#")
            .EnterPassword("not-a-real-secret")
            .Submit();

        using (Assert.EnterMultipleScope())
        {
            Assert.That(result.Message, Is.EqualTo("Received!"));
            Assert.That(result.SubmittedValue("my-text"), Is.EqualTo("Selenium C#"));
            Assert.That(result.SubmittedValue("my-password"), Is.EqualTo("not-a-real-secret"));
        }
    }

    // DisabledInputCannotBeUsed, FieldsStartWithTheirDefaults and
    // TextFieldIsSubmitted as before
}

No locator, URL or wait is left in the test. If the Submit button gets a new class, one line in WebFormPage changes and every test keeps working.

Keep assertions in the tests, not in the page objects. SubmittedPage exposes Message and SubmittedValue; the test decides what they should be. A page object that asserts can only ever check one expectation, and its failures point at the page object instead of the test that cared.

A test calls form.Submit() and immediately reads driver.FindElement(By.Id("message")).Text. It fails now and then with NoSuchElementException. Where does the fix belong?

The race is between the click and the navigation, and the page object that performs the navigation knows how to recognise its end. Putting the wait there fixes every caller at once. A sleep is a guess, and an implicit wait has the side effects described in chapter 2.

The suite is complete as far as local runs go. Next, the same tests run on remote browsers.