Parameterized tests

suggest change

A parameterized test (also called a data-driven test) is one test method that runs many times, once per set of input data. Instead of writing Add_1_2, Add_minus1_1, Add_MaxValue_0 as three near-identical methods, you write one method with parameters and attach the data to it.

All three major .NET test frameworks support this, with different names for the same ideas:

Idea xUnit NUnit MSTest
mark method as data-driven [Theory] [TestCase] / [Test] [TestMethod]
inline constant data [InlineData] [TestCase] [DataRow]
data from a property / method [MemberData] [TestCaseSource] [DynamicData]
data from a separate class [ClassData] [TestCaseSource(typeof(X))] [DynamicData(..., typeof(X))]
strongly typed data TheoryData<T1, ...> TestCaseData tuples, TestDataRow<T>
combinations of values MatrixTheoryData [Values], [Range] -

Examples below use .NET 10 with xUnit v3 (xunit.v3 4.x), NUnit 5 and MSTest 4. Each case shows up as a separate test in test explorers and in dotnet test output, so when one fails you see exactly which input broke it.

All examples test this code:

public static class MathUtil
{
    public static bool IsPrime(int n)
    {
        if (n < 2) return false;
        for (int i = 2; i * i <= n; i++)
            if (n % i == 0) return false;
        return true;
    }

    public static int Add(int a, int b) => a + b;

    public static int Divide(int a, int b) => a / b;
}

public record Money(decimal Amount, string Currency);

public static class Prices
{
    public static Money ApplyDiscount(Money price, int percent) =>
        price with { Amount = Math.Round(price.Amount * (100 - percent) / 100m, 2) };
}

xUnit: Theory and InlineData

In xUnit a regular test is a [Fact]. A parameterized test is a [Theory], and each [InlineData] attribute supplies one set of arguments:

public class PrimeTests
{
    [Theory]
    [InlineData(2)]
    [InlineData(3)]
    [InlineData(13)]
    [InlineData(7919)]
    public void IsPrime_ReturnsTrue_ForPrimes(int n)
    {
        Assert.True(MathUtil.IsPrime(n));
    }

    [Theory]
    [InlineData(1, 2, 3)]
    [InlineData(-1, 1, 0)]
    [InlineData(int.MaxValue, 0, int.MaxValue)]
    public void Add_Works(int a, int b, int expected)
    {
        Assert.Equal(expected, MathUtil.Add(a, b));
    }
}

The values in [InlineData] are matched to method parameters by position. A common convention is to put the expected result last.

When a case fails, the runner prints the argument values, so you know which row broke:

    PrimeTests.Add_Works(a: 2, b: 2, expected: 5) [FAIL]
      Assert.Equal() Failure: Values differ
      Expected: 5
      Actual:   4

Individual rows can be skipped with Skip:

[Theory]
[InlineData(1)]
[InlineData(9)]
[InlineData(100, Skip = "slow on CI")]
public void IsPrime_ReturnsFalse_ForNonPrimes(int n)
{
    Assert.False(MathUtil.IsPrime(n));
}
    PrimeTests.IsPrime_ReturnsFalse_ForNonPrimes(n: 100) [SKIP]
      slow on CI

The limitation of attribute data

Attribute arguments must be compile-time constants: numbers, strings, bool, char, enums, typeof(...), null and arrays of those. You can't put a decimal, a DateTime, a Guid or an object like Money in [InlineData]:

[InlineData(19.99m, 25)]
// error CS0182: An attribute argument must be a constant expression,
// typeof expression or array creation expression of an attribute parameter type

The same rule applies to NUnit's [TestCase] and MSTest's [DataRow]. For such data you use a member (property or method) that returns the test cases.

xUnit: MemberData

[MemberData] points to a static property, field or method on the test class. The classic form returns IEnumerable<object[]>, one array per test case:

public class MemberDataTests
{
    public static IEnumerable<object[]> DiscountCases =>
    [
        [new Money(100m, "USD"), 10, new Money(90m, "USD")],
        [new Money(19.99m, "EUR"), 25, new Money(14.99m, "EUR")],
        [new Money(5m, "PLN"), 0, new Money(5m, "PLN")],
    ];

    [Theory]
    [MemberData(nameof(DiscountCases))]
    public void ApplyDiscount_Works(Money price, int percent, Money expected)
    {
        Assert.Equal(expected, Prices.ApplyDiscount(price, percent));
    }
}

Always use nameof(...) rather than a string literal, so renaming the member doesn't silently break the test.

object[] is not type-safe: if a row has the wrong number or type of values, you find out only at run time.

TheoryData: strongly typed rows

TheoryData<T1, T2, ...> fixes that. It is a collection with an Add(T1, T2, ...) method, so you can use collection initializer syntax and the compiler checks every row:

public static TheoryData<int, int, int> DivideCases => new()
{
    { 10, 2, 5 },
    { 7, 2, 3 },
    { -9, 3, -3 },
};

[Theory]
[MemberData(nameof(DivideCases))]
public void Divide_Works(int a, int b, int expected)
{
    Assert.Equal(expected, MathUtil.Divide(a, b));
}

Writing { 10, "2", 5 } is now a compile error. Prefer TheoryData over object[] in new code.

MemberData with arguments

If the member is a method, you can pass arguments to it after the name. This is useful for generated data:

public static TheoryData<int> FirstPrimes(int count)
{
    var data = new TheoryData<int>();
    for (int n = 2; data.Count < count; n++)
        if (MathUtil.IsPrime(n)) data.Add(n);
    return data;
}

[Theory]
[MemberData(nameof(FirstPrimes), 5)]
public void Primes_AreOdd_ExceptTwo(int p)
{
    Assert.True(p == 2 || p % 2 == 1);
}

This produces 5 test cases: 2, 3, 5, 7 and 11.

To use data defined in another class, add MemberType:

[MemberData(nameof(SharedData.Composites), MemberType = typeof(SharedData))]

Per-row display name and skip: TheoryDataRow

xUnit v3 adds TheoryDataRow<...>, which wraps one row and lets you set metadata on it, such as a display name, a skip reason, traits or a timeout:

public static TheoryData<string, int> Lengths => new()
{
    new TheoryDataRow<string, int>("", 0),
    new TheoryDataRow<string, int>("abc", 3) { TestDisplayName = "three letters" },
    new TheoryDataRow<string, int>("héllo", 5) { Skip = "unicode not ready" },
};

[Theory]
[MemberData(nameof(Lengths))]
public void Length_Works(string s, int expected) => Assert.Equal(expected, s.Length);
    MemberDataTests.Length_Works(s: "héllo", expected: 5) [SKIP]
      unicode not ready

All combinations: MatrixTheoryData

MatrixTheoryData (xUnit v3) generates the cross product of several sets of values:

public static MatrixTheoryData<int, int> AddMatrix => new([1, 2, 3], [10, 20]);

[Theory]
[MemberData(nameof(AddMatrix))]
public void Add_IsCommutative(int a, int b) =>
    Assert.Equal(MathUtil.Add(a, b), MathUtil.Add(b, a));

This runs 3 x 2 = 6 cases: (1,10), (1,20), (2,10), (2,20), (3,10), (3,20).

xUnit: ClassData

[ClassData] takes a type whose instances provide the data. The simplest way is to derive from TheoryData<...> and add rows in the constructor:

public class DivideByZeroData : TheoryData<int>
{
    public DivideByZeroData()
    {
        Add(1);
        Add(0);
        Add(int.MinValue);
    }
}

public class ClassDataTests
{
    [Theory]
    [ClassData(typeof(DivideByZeroData))]
    public void Divide_ByZero_Throws(int a)
    {
        Assert.Throws<DivideByZeroException>(() => MathUtil.Divide(a, 0));
    }
}

Use ClassData when the same data set is shared by several test classes, or when building it takes enough code that it deserves its own class (e.g. reading test cases from a file).

Note on serialization

Test explorers (Visual Studio, Rider, VS Code) list each data row as a separate test only if xUnit can serialize the arguments at discovery time. Primitive types, strings, enums, DateTime, Guid etc. work. For custom types like Money, xUnit falls back to showing a single test for the whole theory, and runs all rows when you run it. Results are still correct; you just can't run one row in isolation from the IDE. To get per-row tests for your own types, implement IXunitSerializable (or register an IXunitSerializer in v3).

NUnit: TestCase

NUnit's equivalent of [InlineData] is [TestCase]. It doesn't need a separate [Test] attribute:

public class PrimeTests
{
    [TestCase(2)]
    [TestCase(3)]
    [TestCase(13)]
    [TestCase(7919)]
    public void IsPrime_ReturnsTrue_ForPrimes(int n)
    {
        Assert.That(MathUtil.IsPrime(n), Is.True);
    }
}

A nice NUnit feature is ExpectedResult: the test method returns a value and NUnit compares it to the expected value for you. You can also set the test name, or ignore a single case:

[TestCase(1, 2, ExpectedResult = 3)]
[TestCase(-1, 1, ExpectedResult = 0)]
[TestCase(2, 2, ExpectedResult = 4, TestName = "Two plus two")]
[TestCase(0, 0, ExpectedResult = 0, Ignore = "just because")]
public int Add(int a, int b) => MathUtil.Add(a, b);
  Passed Add(1,2) [8 ms]
  Passed Add(-1,1) [< 1 ms]
  Passed Two plus two [< 1 ms]
  Skipped Add(0,0) [< 1 ms]

[TestCase] also has Category, Description, Explicit and Author properties.

NUnit: Values, Range and combinations

NUnit can put data attributes directly on parameters. By default it runs every combination (combinatorial):

[Test]
public void Add_IsCommutative([Values(1, 2, 3)] int a, [Values(10, 20)] int b)
{
    Assert.That(MathUtil.Add(a, b), Is.EqualTo(MathUtil.Add(b, a)));
}
  Passed Add_IsCommutative(1,10)
  Passed Add_IsCommutative(1,20)
  Passed Add_IsCommutative(2,10)
  Passed Add_IsCommutative(2,20)
  Passed Add_IsCommutative(3,10)
  Passed Add_IsCommutative(3,20)

[Range(from, to)] generates a range of numbers (inclusive):

[Test]
public void IsPrime_ForSmallNumbers([Range(-2, 1)] int n)
{
    Assert.That(MathUtil.IsPrime(n), Is.False);
}

This runs for -2, -1, 0 and 1. [Range] also accepts a step, e.g. [Range(0, 100, 10)].

Add [Sequential] to pair values by position instead of combining them:

[Test, Sequential]
public void Add_Sequential([Values(1, 2, 3)] int a,
                           [Values(10, 20, 30)] int b,
                           [Values(11, 22, 33)] int expected)
{
    Assert.That(MathUtil.Add(a, b), Is.EqualTo(expected));
}

This runs 3 cases: (1,10,11), (2,20,22), (3,30,33). There is also [Pairwise], which generates a smaller set that covers every pair of values at least once. It's useful when the full cross product would be huge.

[Random(min, max, count)] generates random values, but random inputs make failures hard to reproduce, so use it sparingly.

NUnit: TestCaseSource and ValueSource

[TestCaseSource] is NUnit's MemberData. The source can be a static field, property or method returning object[] rows:

static object[] DivideCases =
[
    new object[] { 10, 2, 5 },
    new object[] { 7, 2, 3 },
    new object[] { -9, 3, -3 },
];

[TestCaseSource(nameof(DivideCases))]
public void Divide(int a, int b, int expected) =>
    Assert.That(MathUtil.Divide(a, b), Is.EqualTo(expected));

For more control, return TestCaseData objects. They have a fluent API for the expected result, name, category, ignore reason etc.:

static IEnumerable<TestCaseData> DiscountCases()
{
    yield return new TestCaseData(new Money(100m, "USD"), 10)
        .Returns(new Money(90m, "USD"));
    yield return new TestCaseData(new Money(19.99m, "EUR"), 25)
        .Returns(new Money(14.99m, "EUR"))
        .SetName("Quarter off euros");
    yield return new TestCaseData(new Money(5m, "PLN"), 0)
        .Returns(new Money(5m, "PLN"))
        .SetCategory("Edge");
}

[TestCaseSource(nameof(DiscountCases))]
public Money ApplyDiscount(Money price, int percent) =>
    Prices.ApplyDiscount(price, percent);
  Passed ApplyDiscount(Money { Amount = 100, Currency = USD },10)
  Passed Quarter off euros
  Passed ApplyDiscount(Money { Amount = 5, Currency = PLN },0)

Since Money is a record, it has value equality and a readable ToString(), which makes it work well both for comparing results and in test names.

[ValueSource] is the per-parameter version, like [Values] but with data from a member:

static IEnumerable<int> Dividends() => [1, 0, int.MinValue];

[Test]
public void Divide_ByZero_Throws([ValueSource(nameof(Dividends))] int a) =>
    Assert.Throws<DivideByZeroException>(() => MathUtil.Divide(a, 0));

To keep data in a separate class, pass a type that implements IEnumerable:

public class CompositeNumbers : IEnumerable<TestCaseData>
{
    public IEnumerator<TestCaseData> GetEnumerator()
    {
        foreach (var n in new[] { 4, 6, 8, 9, 10 })
            yield return new TestCaseData(n);
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() =>
        GetEnumerator();
}

public class ClassSourceTests
{
    [TestCaseSource(typeof(CompositeNumbers))]
    public void NotPrime(int n) => Assert.That(MathUtil.IsPrime(n), Is.False);
}

Alternatively use [TestCaseSource(typeof(OtherClass), nameof(OtherClass.Cases))] to point at a static member of another class.

MSTest: DataRow

In MSTest you keep [TestMethod] and add one [DataRow] per case:

[TestClass]
public sealed class PrimeTests
{
    [TestMethod]
    [DataRow(2)]
    [DataRow(3)]
    [DataRow(13)]
    [DataRow(7919)]
    public void IsPrime_ReturnsTrue_ForPrimes(int n)
    {
        Assert.IsTrue(MathUtil.IsPrime(n));
    }

    [TestMethod]
    [DataRow(1, 2, 3)]
    [DataRow(-1, 1, 0)]
    [DataRow(2, 2, 4, DisplayName = "Two plus two")]
    [DataRow(0, 0, 0, IgnoreMessage = "just because")]
    public void Add_Works(int a, int b, int expected)
    {
        Assert.AreEqual(expected, MathUtil.Add(a, b));
    }
}
  Passed Add_Works (1,2,3)
  Passed Add_Works (-1,1,0)
  Passed Two plus two
  Skipped Add_Works (0,0,0)

MSTest: DynamicData

[DynamicData] reads cases from a static property or method. Since MSTest 3.7 it auto-detects whether the member is a property or a method, and besides IEnumerable<object[]> it accepts tuples, which gives you type safety:

[TestClass]
public sealed class DynamicDataTests
{
    public static IEnumerable<(Money Price, int Percent, Money Expected)> DiscountCases =>
    [
        (new Money(100m, "USD"), 10, new Money(90m, "USD")),
        (new Money(19.99m, "EUR"), 25, new Money(14.99m, "EUR")),
        (new Money(5m, "PLN"), 0, new Money(5m, "PLN")),
    ];

    [TestMethod]
    [DynamicData(nameof(DiscountCases))]
    public void ApplyDiscount_Works(Money price, int percent, Money expected)
    {
        Assert.AreEqual(expected, Prices.ApplyDiscount(price, percent));
    }

    public static IEnumerable<object[]> DivideCases()
    {
        yield return [10, 2, 5];
        yield return [7, 2, 3];
        yield return [-9, 3, -3];
    }

    [TestMethod]
    [DynamicData(nameof(DivideCases))]
    public void Divide_Works(int a, int b, int expected)
    {
        Assert.AreEqual(expected, MathUtil.Divide(a, b));
    }
}

TestDataRow<T> wraps a row and adds per-row metadata, similar to xUnit's TheoryDataRow:

public static IEnumerable<TestDataRow<int>> Dividends =>
[
    new(1),
    new(0) { DisplayName = "zero divided by zero" },
    new(int.MinValue) { IgnoreMessage = "flaky" },
];

[TestMethod]
[DynamicData(nameof(Dividends))]
public void Divide_ByZero_Throws(int a)
{
    Assert.ThrowsExactly<DivideByZeroException>(() => MathUtil.Divide(a, 0));
}

To read data from a different class, pass its type as the second argument:

public static class SharedData
{
    public static IEnumerable<int> Composites => [4, 6, 8, 9, 10];
}

[TestClass]
public sealed class OtherClassTests
{
    [TestMethod]
    [DynamicData(nameof(SharedData.Composites), typeof(SharedData))]
    public void NotPrime(int n) => Assert.IsFalse(MathUtil.IsPrime(n));
}

A single-parameter test can return IEnumerable<int> directly, without wrapping each value in an array.

Tips

Running a single case from the command line works with the normal filter syntax, e.g. dotnet test --filter "FullyQualifiedName~Add_Works". See Testing in CI for running tests in a pipeline.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents