Exit course
Chapter 4 of 10 Intermediate 7 min read 2 quick checks Updated

NUnit fixtures, attributes and [TestCase]

On this page
  1. The lifecycle attributes
  2. A driver factory
  3. A base class
  4. [TestCase]: one method, many inputs
  5. Categories, Explicit and Ignore
  6. TestContext

Two test classes in, the duplication is already visible: each has its own driver field, its own SetUp that starts Chrome and its own TearDown that quits it. This chapter moves the browser into a base class, makes the browser choice configurable, and uses NUnit's attributes to run one test method with many inputs.

The lifecycle attributes#

NUnit calls methods in a fixed order around each test. A fixture is simply a class that contains tests.

Attribute Runs Typical use in a browser suite
[OneTimeSetUp] once, before the first test in the fixture expensive shared setup, such as creating test data through an API
[SetUp] before every test start a browser, open the page under test
[Test], [TestCase] the test itself
[TearDown] after every test, pass or fail screenshot on failure, quit the browser
[OneTimeTearDown] once, after the last test in the fixture clean up shared data

A class marked [SetUpFixture] with its own [OneTimeSetUp] runs once for every fixture in its namespace, or for the whole assembly if it has no namespace.

One browser per test, not per fixture. It is tempting to start the browser in [OneTimeSetUp] to save a few seconds. Then cookies, local storage and the current page leak from one test into the next, the order of tests starts to matter, and chapter 7's parallel runs become impossible. Start a fresh browser in [SetUp] and quit it in [TearDown].

When a fixture inherits from a base class, NUnit runs the base class's [SetUp] before the derived class's, and the derived [TearDown] before the base one. That is what makes a base class work: the browser exists before the test class's own setup runs.

A driver factory#

First, put browser creation in one place and read the browser from an environment variable, so the same tests can run on Chrome or Firefox without a code change. Create Support/DriverFactory.cs:

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;

namespace SeleniumCourse.Support;

public static class DriverFactory
{
    public static string Browser =>
        Environment.GetEnvironmentVariable("BROWSER") ?? "chrome";

    private static bool Headless =>
        Environment.GetEnvironmentVariable("HEADLESS") == "1";

    public static IWebDriver Create()
    {
        switch (Browser)
        {
            case "chrome":
                var chrome = new ChromeOptions();
                if (Headless) chrome.AddArguments("--headless=new", "--window-size=1920,1080");
                return new ChromeDriver(chrome);
            case "firefox":
                var firefox = new FirefoxOptions();
                if (Headless) firefox.AddArgument("-headless");
                return new FirefoxDriver(firefox);
            default:
                throw new ArgumentException($"Unknown BROWSER '{Browser}'");
        }
    }
}

Environment variables rather than command-line arguments because they work the same way in a terminal, an IDE run configuration and a CI job, and dotnet test passes them through to the test process unchanged.

The --window-size argument is not decoration. Our first headless run failed four tests with:

OpenQA.Selenium.ElementClickInterceptedException : element click intercepted: Element is not clickable at point (158, 857)

Headless Chrome starts with a small default window, and in it the form's Submit button sat under another element. With a desktop-sized window all tests passed. When a test passes headed and fails headless, check the window size first.

A base class#

Create Support/BaseTest.cs:

using OpenQA.Selenium;

namespace SeleniumCourse.Support;

public abstract class BaseTest
{
    protected IWebDriver Driver { get; private set; } = null!;

    [SetUp]
    public void StartBrowser()
    {
        Driver = DriverFactory.Create();
    }

    [TearDown]
    public void StopBrowser()
    {
        Driver.Quit();
    }
}

Test classes now inherit it, and their own [SetUp] only does what is specific to them:

public class WaitTests : BaseTest
{
    private const string Dynamic = "https://www.selenium.dev/selenium/web/dynamic.html";

    [SetUp]
    public void OpenPage() => Driver.Navigate().GoToUrl(Dynamic);

    // tests as before, using Driver instead of driver
}
dotnet test                                # Chrome
BROWSER=firefox HEADLESS=1 dotnet test     # headless Firefox

On Windows PowerShell, set the variable first: $env:BROWSER = "firefox".

To save time, a fixture starts Chrome in [OneTimeSetUp] and its tests share it. A test that checks the empty shopping cart now fails only when it runs after the "add to cart" test. What is the fix?

A shared browser carries cookies, storage and the current page between tests, making results depend on order. Ordering or clearing one piece of state treats the symptom; the next leak will be somewhere else. A browser per test removes the whole class of problem and is what parallel runs need anyway.

[TestCase]: one method, many inputs#

The form's dropdown has three options. Rather than three copies of a test, write one with parameters and one [TestCase] per input. Create Tests/WebFormTests.cs:

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

namespace SeleniumCourse.Tests;

[TestFixture]
[Category("form")]
public class WebFormTests : BaseTest
{
    private const string WebForm = "https://www.selenium.dev/selenium/web/web-form.html";

    [SetUp]
    public void OpenForm()
    {
        Driver.Navigate().GoToUrl(WebForm);
    }

    [TestCase("One", "1")]
    [TestCase("Two", "2")]
    [TestCase("Three", "3")]
    public void DropdownSelectionIsSubmitted(string label, string value)
    {
        new SelectElement(Driver.FindElement(By.Name("my-select"))).SelectByText(label);
        Driver.FindElement(By.CssSelector("button[type='submit']")).Click();

        new WebDriverWait(Driver, TimeSpan.FromSeconds(5))
            .Until(d => d.Title == "Web form - target page");
        Assert.That(Driver.Url, Does.Contain($"my-select={value}"));
    }

    [Test]
    public void DisabledInputCannotBeUsed()
    {
        IWebElement disabled = Driver.FindElement(By.Name("my-disabled"));

        Assert.That(disabled.Enabled, Is.False);
    }
}

Each [TestCase] is a separate test with its own browser, its own result and its own name in the output:

  Passed DisabledInputCannotBeUsed [1 s]
  Passed DropdownSelectionIsSubmitted("One","1") [1 s]
  Passed DropdownSelectionIsSubmitted("Two","2") [1 s]
  Passed DropdownSelectionIsSubmitted("Three","3") [1 s]

The form submits with a GET request, so the chosen values end up in the URL of the target page, which is what the assertion reads. The wait on the title makes sure the browser has actually navigated before the URL is checked.

[TestCase] arguments must be compile-time constants. When the data is computed, lives in a file, or is more than a few values, use [TestCaseSource] with a static member instead:

private static readonly object[] TextFields =
[
    new object[] { "my-text", "Selenium" },
    new object[] { "my-textarea", "NUnit" },
];

[TestCaseSource(nameof(TextFields))]
public void TextFieldIsSubmitted(string field, string value)
{
    Driver.FindElement(By.Name(field)).SendKeys(value);
    Driver.FindElement(By.CssSelector("button[type='submit']")).Click();

    new WebDriverWait(Driver, TimeSpan.FromSeconds(5))
        .Until(d => d.Title == "Web form - target page");
    Assert.That(Driver.Url, Does.Contain($"{field}={value}"));
}

You want to run a login test for twenty user accounts that a helper method reads from a JSON file. Which attribute fits?

Attribute arguments must be constants, so [TestCase] cannot call a method. A loop inside one test stops at the first failing account and reports a single result; [TestCaseSource] gives each account its own test, name and result.

Categories, Explicit and Ignore#

[Category("form")] on the class (or a method) tags tests so you can select them:

dotnet test --filter "Category=form"
dotnet test --filter "Category!=slow"

Categories are a better way to build a "smoke" subset than lists of test names, because new tests join the subset by being tagged. Two related attributes: [Explicit] keeps a test out of normal runs unless it is selected by name or filter, which suits a long data-migration check; [Ignore("reason")] skips a test and shows the reason in every run. Use [Ignore] sparingly and always with a reason and ideally a ticket number, or skipped tests pile up unnoticed.

TestContext#

Inside a test or a setup method, TestContext.CurrentContext tells you where you are:

  • Test.Name: the test's name, including [TestCase] arguments, such as DropdownSelectionIsSubmitted("Two","2");
  • Result.Outcome.Status: in [TearDown], whether the test passed or failed;
  • WorkDirectory: a folder for files the run produces.

The next chapter uses all three to take a screenshot whenever a test fails.