skip to content

In NUnit 5, how does [TestCase] parameterise a test, and what do ExpectedResult and NUnit's argument conversion add?

level: juniorimportance: must knowfreq 70%

answer

  1. one attribute per row
  2. attribute arguments are compile-time constants
  3. decimal parameters from int or double literals
  4. ExpectedResult needs a return value
  5. TestName and Category per row

basics

~20 s

[TestCase] supplies one row of constant arguments per attribute; NUnit turns each row into its own test. ExpectedResult lets the method return the value NUnit compares, and NUnit converts literals such as 0.5 into decimal parameters.

solid answer

~40 s

Each `[TestCase(...)]` on a method is one test case: NUnit passes the attribute's arguments to the method's parameters and reports each row separately, so one failing row does not hide the others. The method needs no `[Test]`, and the class needs no `[TestFixture]`. Attribute arguments must be compile-time constants, so a `decimal` cannot be written directly; NUnit converts an `int` or `double` literal (or a string) to the parameter's type, so `[TestCase(0.5, Zone.Europe)]` feeds a `decimal weightKg`. Setting `ExpectedResult = 9.60` lets the method **return** its result and NUnit asserts it with `Is.EqualTo`; a non-void method without `ExpectedResult` is not runnable, and a void method with one is rejected. `TestName`, `Category`, `Ignore` and `Description` decorate a single row.

code

csharp · 15 lines
csharp
public class ExpressSurchargeTests
{
    private readonly ShippingCostCalculator _calculator = new();

    [TestCase(2, Zone.Domestic, TestName = "Domestic express, 2 kg")]
    [TestCase(0.5, Zone.Europe, Category = "Europe")]
    [TestCase(30, Zone.International, Ignore = "Freight rules not built yet")]
    public void Express_adds_flat_surcharge(decimal weightKg, Zone zone)
    {
        var standard = _calculator.Calculate(weightKg, zone, express: false);
        var express = _calculator.Calculate(weightKg, zone, express: true);

        Assert.That(express - standard, Is.EqualTo(5.00m));
    }
}

go deeper

for a junior

Recall that each [TestCase] attribute is one row and one reported test, and that ExpectedResult pairs with a method that returns its result.

for a middle

Explain the constant-argument limit, how NUnit converts int, double and string literals into decimal or DateTime parameters, and the build-time rules on return values.

for a senior

Spot where ExpectedResult's double comparison or a missing row hides a defect in money calculations, and know when rows should move to [TestCaseSource].

for a principal

Set a team convention for when inline rows stop being readable and a shared data source or generated grid takes over.

## One attribute, one test case `[TestCase]` is NUnit's inline data attribute. Every `[TestCase(...)]` placed on a method becomes one **test case**: NUnit builds a separate test for it, with the arguments in its name, its own `[SetUp]`/`[TearDown]` run and its own pass or fail in the report. - The method does not need `[Test]`; `[TestCase]` is enough to make it a test. - The class does not need `[TestFixture]`; a class containing `[TestCase]` methods is treated as a fixture. - The arguments map to parameters by position, and the count must match (or the extra parameters must be optional). For a shipping-cost rule engine with `Calculate(decimal weightKg, Zone zone, bool express)`, three rows test three zones without three copies of the test body. ## Constants only, and how NUnit fills the gap C# allows only compile-time constants of a few types as attribute arguments: numbers, `bool`, `char`, `string`, enums, `Type` and arrays of those. **`decimal` is not one of them**, and neither is `DateTime`. NUnit bridges this when it binds the row to the method: 1. It looks at the parameter's actual type. 2. If the argument is already that type, it uses it as-is. 3. Otherwise it applies its own numeric conversions (for example `int` or `double` to `decimal`, or `int` to `byte`), or the target type's `TypeConverter` from a string, using the invariant culture. So `[TestCase(0.5, Zone.Europe)]` reaches a `decimal weightKg` parameter as `0.5m`, and `[TestCase("2026-10-01")]` can feed a `DateTime`. When even that is not enough (an object graph, a computed value), the data moves to `[TestCaseSource]`. ## ExpectedResult: returning instead of asserting Instead of writing `Assert.That` in every row, a test can **return** the value under test and declare the expected value on the attribute: ```csharp [TestCase(2, Zone.Domestic, ExpectedResult = 6.90)] [TestCase(0.5, Zone.Europe, ExpectedResult = 9.60)] [TestCase(10, Zone.International, ExpectedResult = 27.00)] public decimal Standard_rate(decimal weightKg, Zone zone) => _calculator.Calculate(weightKg, zone, express: false); ``` NUnit runs the method and checks the return value with `Assert.That(result, Is.EqualTo(expected))`. Two rules are enforced when the test is built: - A method with a **non-void return** and no `ExpectedResult` is marked not runnable ("Method has non-void return value, but no result is expected"). - A **void** method with an `ExpectedResult` is also not runnable. One subtlety: `ExpectedResult` is **not converted** the way arguments are. The literal `6.90` stays a `double`, and NUnit's numeric equality compares a `double` and a `decimal` as doubles. That is fine for values like these, but for exact money checks with many decimal places, assert a `decimal` inside the method or move the rows to `[TestCaseSource]` with `decimal` values. ## Per-row options | Property | Effect on that row | |---|---| | `TestName` | replaces the generated display name | | `Category` | adds a category for filtering | | `Ignore` / `IgnoreReason` | skips the row with a reason | | `Explicit` | runs the row only when selected explicitly | | `Description`, `Author`, `TestOf` | metadata in the result | | `TypeArgs` | type arguments for a generic test method | NUnit 5 also ships generic forms such as `[TestCase<decimal, Zone>(...)]`, which let the compiler check argument types against the attribute's type parameters. ## How rows show up in a run Each row is a separate node under the method in the test tree and in the results file: - The generated name contains the argument values, so a failing row is identified without opening the code; `TestName` replaces it when the values are unreadable. - A failure in one row does not stop the others. Three rows with one wrong rate report one failure and two passes, which is the main advantage over a loop inside a single `[Test]`. - Each row can be selected and re-run on its own from an IDE or by a name filter, and each gets its own `[SetUp]` and `[TearDown]` call. - A row that cannot be bound (wrong argument count, an argument NUnit cannot convert) is reported as not runnable on its own, while valid rows still run. ## When [TestCase] is the right tool - A handful of rows of simple constants: a rate per zone, a boundary weight, an invalid input. - Rows that read well in the attribute list, so a reviewer sees the table of cases at a glance. - Not for data that must be computed, shared across classes or built from objects; that is `[TestCaseSource]`'s job. - Not for crossing every value of several parameters; `[Values]` and `[Combinatorial]` generate that grid instead of hand-writing it.

  • Why can't you write 9.60m directly in an NUnit [TestCase] attribute?
    C# attribute arguments must be compile-time constants of a few primitive types, and `decimal` is not among them. NUnit compensates by converting `int`, `double` or string arguments to the parameter's type when it binds the row, so `9.60` reaches a `decimal` parameter correctly.
  • What does NUnit do with a [TestCase] method that returns decimal but sets no ExpectedResult?
    It marks the test not runnable with the reason "Method has non-void return value, but no result is expected". Either set `ExpectedResult` on each row or make the method `void` and assert inside it.
  • Is ExpectedResult converted to the method's return type like the arguments are?
    No. NUnit converts arguments to parameter types, but compares `ExpectedResult` as written with `Is.EqualTo`. A `double` literal against a `decimal` return is compared numerically as `double`. For exact decimal checks, assert inside the method or supply decimals from `[TestCaseSource]`.

  • Every [TestCase] method also needs [Test], or NUnit ignores it
  • decimal can be written directly as an attribute argument
  • All rows of a [TestCase] method pass or fail together
  • A method returning a value runs fine without ExpectedResult
  • ExpectedResult literals are converted to the return type like arguments
  • [Theory] is NUnit's attribute for inline rows of constants