skip to content

In NUnit 5, when do you move from [TestCase] to [TestCaseSource], and why must the source member be static?

level: middleimportance: should knowfreq 48%

answer

  1. data that is not a constant
  2. nameof on the source member
  3. TestCaseData with Returns and SetName
  4. built during discovery, not at run time
  5. a Type argument for a shared source class

basics

~20 s

[TestCaseSource] names a static member that yields the rows, for data attributes cannot hold: exact decimals, objects, computed or shared rows. It must be static because NUnit builds the cases during discovery, before any fixture instance or setup exists.

solid answer

~40 s

Use `[TestCaseSource(nameof(Cases))]` when the rows need values an attribute cannot carry (a `decimal`, a parcel object, a list), are computed, or are shared by several fixtures through `[TestCaseSource(typeof(ShippingCases), nameof(ShippingCases.Express))]`. The source returns an `IEnumerable` of `object[]` rows or, better, `TestCaseData`, which adds `.Returns(...)`, `.SetName(...)`, `.SetArgDisplayNames(...)`, `.SetCategory(...)` and `.Ignore(...)` per row. NUnit evaluates the source while it **builds the test tree**, before any fixture instance or `[SetUp]` runs. That is why the member must be static: a non-static source makes the test not runnable with the message that the source "must refer to a static field, property or method". It also means the source cannot read fields that setup methods assign.

code

csharp · 18 lines
csharp
public class ExpressRateTests
{
    private readonly ShippingCostCalculator _calculator = new();

    private static IEnumerable<TestCaseData> ExpressCases()
    {
        yield return new TestCaseData(2m, Zone.Domestic)
            .Returns(11.90m).SetName("Domestic express, 2 kg");
        yield return new TestCaseData(2m, Zone.Europe)
            .Returns(16.40m).SetName("Europe express, 2 kg");
        yield return new TestCaseData(0m, Zone.Europe)
            .Ignore("Zero-weight rule under review");
    }

    [TestCaseSource(nameof(ExpressCases))]
    public decimal Express_rate(decimal weightKg, Zone zone) =>
        _calculator.Calculate(weightKg, zone, express: true);
}

go deeper

for a junior

Recall that [TestCaseSource] names a member that yields rows, and that TestCaseData carries the arguments plus Returns and SetName.

for a middle

Explain why the member must be static: NUnit enumerates it at discovery, before any instance or setup exists, so it cannot read setup state.

for a senior

Design sources that are cheap and deterministic, yield case descriptions rather than live resources, and are shared across fixtures by type.

for a principal

Decide where shared case catalogues live and who owns them, so several teams' tests draw on one reviewed set of business rules.

## What [TestCaseSource] solves `[TestCase]` rows are attribute arguments, so they are limited to compile-time constants. Real rule engines need more: - **Exact `decimal` values** for money, written as `12.40m` rather than a converted `double`. - **Objects** such as a `Parcel` with dimensions, a destination and a declared value. - **Computed rows**, for example every zone crossed with a list of weights read from a fixture file. - **Shared rows**, used by the calculator tests and by the quote API tests alike. `[TestCaseSource]` points the test at a **member that produces the rows**. Each item it yields becomes one test case, exactly like one `[TestCase]` attribute. ## Pointing at the source | Form | Meaning | |---|---| | `[TestCaseSource(nameof(Cases))]` | a static field, property or method on the same class | | `[TestCaseSource(typeof(ShippingCases), nameof(ShippingCases.Express))]` | a static member on another class | | `[TestCaseSource(nameof(CasesFor), new object[] { Zone.Europe })]` | a static **method** called with arguments | | `[TestCaseSource(typeof(ShippingCases))]` | the class itself is enumerable and supplies the rows | Using `nameof` keeps the reference refactor-safe; a misspelt string only fails when the tests are loaded. Passing arguments is allowed only when the source is a method; giving arguments to a field or property makes the test not runnable with an explanatory message. ## What the source yields 1. **`object[]` per row**: the array is unpacked into the method's parameters. 2. **A single value per row** for a one-parameter test. 3. **`TestCaseData`** (the usual choice): wraps the arguments and adds fluent per-row settings: - `.Returns(16.40m)` - the expected return value, like `ExpectedResult` - `.SetName("Europe express, 2 kg")` - the display name - `.SetArgDisplayNames("2 kg", "Europe")` - how arguments appear in the name - `.SetCategory("Express")`, `.SetDescription(...)`, `.SetProperty(...)` - `.Ignore("reason")`, `.Explicit()` NUnit 5 also has typed variants (`TestCaseData.Create(...)` returning `TestCaseData<T1, T2>`, and `TestCaseDataWithReturn<...>`) so the compiler checks argument types. ## Why static: the source runs at discovery NUnit does its work in two phases: 1. **Discovery (loading).** NUnit reflects over the assembly, builds the tree of fixtures and test cases, and reports it to the runner. To know how many cases a `[TestCaseSource]` method has, it must **enumerate the source now**. 2. **Execution.** NUnit creates the fixture instance, runs `[OneTimeSetUp]`, then `[SetUp]` and each test. At discovery there is **no fixture instance**, so only static members can be read. NUnit checks this and marks the test not runnable with "The sourceName specified on a TestCaseSourceAttribute must refer to a static field, property or method." Two consequences follow: - A source **cannot depend on setup**: a field assigned in `[OneTimeSetUp]` is still unassigned when the source runs. - A source should be **cheap and deterministic**. It runs every time tests are listed, including in an IDE's test explorer, and changing data between discovery and execution produces confusing results. If a row needs a live resource (a database row, a running server), the source should yield a **description** of the case (an id, a file name) and the test body should fetch the resource after setup has run. ## [TestCase] or [TestCaseSource]? | Need | `[TestCase]` | `[TestCaseSource]` | |---|---|---| | Exact `decimal` literals | converted from `int`/`double` | written as `16.40m` | | Objects and collections as arguments | not possible | yes | | Rows shared by several fixtures | copy the attributes | reference one static member by type | | Rows visible beside the test | yes, in the attribute list | no, in another member | | Per-row name, category, ignore | attribute properties | `TestCaseData` methods | A reasonable rule: start with `[TestCase]` while rows are a few readable constants, and move to a source once rows need objects, exact decimals or reuse. ## Other rules worth knowing - `[TestCaseSource]` on a method **without parameters** is not runnable; there is nothing to bind the rows to. - An **empty source** yields no cases. NUnit then reports the method as inconclusive with "No test cases were provided" (a `[NoTests]` attribute can change that status), which is easy to overlook in a long run. - For **one parameter's** values rather than whole rows, `[ValueSource]` on the parameter is the per-parameter counterpart.

  • A [TestCaseSource] method reads a field assigned in [OneTimeSetUp] and gets null. Why?
    NUnit enumerates the source during discovery, before any fixture instance exists or any setup runs. The source must be static and self-contained. Yield identifiers or file names from the source and resolve the live resource inside the test body, after setup.
  • How do you share one set of NUnit test cases between two fixtures?
    Put the static member on a separate class and reference it with `[TestCaseSource(typeof(ShippingCases), nameof(ShippingCases.Express))]` on each test. Both fixtures then enumerate the same rows.
  • What does TestCaseData.Returns do in NUnit?
    It sets the expected return value for that row, the source-based equivalent of `ExpectedResult` on `[TestCase]`. The test method returns its result and NUnit compares it with `Is.EqualTo`. Unlike an attribute literal, the value can be an exact `decimal` such as `16.40m`.

  • A [TestCaseSource] member can be an instance property filled in [SetUp]
  • NUnit enumerates the source after [OneTimeSetUp] has run
  • [TestCaseSource] works on a test method with no parameters
  • Arguments can be passed to a source field or property
  • Rows from a source share one result, unlike [TestCase] rows
  • [TestFixtureSource] supplies rows to a single test method