skip to content

In xunit.v3, when do you move a theory from [InlineData] to [MemberData] or [ClassData], and what does TheoryData<T> add?

level: middleimportance: should knowfreq 52%

answer

  1. attribute arguments must be constants
  2. decimal and DateTime cannot be inline
  3. public static member named with nameof
  4. [ClassData(typeof(T))] for reusable rows
  5. TheoryData<T1, T2> type-checks each row

basics

~20 s

Move off [InlineData] when values cannot be attribute constants (decimal, DateTime, objects), are computed, or are shared. [MemberData] reads a public static member, [ClassData] instantiates a reusable data class, and TheoryData<T1, T2> makes the compiler check every row.

solid answer

~40 s

`[InlineData]` only takes what C# allows in an attribute: numbers, strings, `bool`, `char`, enums, `typeof`, `null` and one-dimensional arrays. A tax table in `decimal`, a `DateOnly` effective date or a `TaxReturn` object cannot go there. `[MemberData(nameof(BracketEdges))]` reads a `public static` property, field or method on the test class; `MemberType` points at another class, and extra attribute arguments are passed to a method. `[ClassData(typeof(JointFilerCases))]`, or `[ClassData<JointFilerCases>]`, instantiates a class that enumerates the rows, which suits data several test classes reuse. In xunit.v3 a member may yield `object?[]` rows, tuples or `ITheoryDataRow` values, but `TheoryData<decimal, decimal>` is the usual choice: its collection initializer is checked against the parameter types at compile time, whereas a malformed `object[]` row fails only when it runs. `TheoryDataRow<...>` adds per-row `Skip`, `TestDisplayName`, `Label` and traits.

code

csharp · 18 lines
csharp
public class BracketEdgeTests
{
    private readonly TaxCalculator _calculator = new(TaxBrackets.Default2026);

    public static TheoryData<decimal, decimal> BracketEdges => new()
    {
        { 10_000.00m, 0.00m },
        { 40_000.00m, 6_000.00m },
        { 40_000.50m, 6_000.20m },
        new TheoryDataRow<decimal, decimal>(250_000m, 90_000m)
            { Skip = "2027 top rate not confirmed" },
    };

    [Theory]
    [MemberData(nameof(BracketEdges))]
    public void Tax_at_bracket_edges(decimal income, decimal expectedTax) =>
        Assert.Equal(expectedTax, _calculator.Calculate(income));
}

go deeper

for a junior

Know the three data attributes and that decimals, dates and objects cannot be written inside [InlineData].

for a middle

Explain the public static member rule, MemberType and method arguments, and why TheoryData<T1, T2> catches a bad row at compile time.

for a senior

Choose sources for maintainability: typed rows for money, shared [ClassData] tables, per-row skips with TheoryDataRow, and no culture-dependent string conversions.

for a principal

Treat test data as code a team owns: decide where shared tables live, how they are typed, and how a rule change propagates to every suite that depends on them.

## Why [InlineData] runs out `[InlineData]` is an attribute, and C# attribute arguments must be compile-time constants of a short list of types. That rules out several things a tax-bracket suite needs: - **`decimal` amounts**: `[InlineData(40_000.50m, 6_000.20m)]` does not compile, because `decimal` is not a valid attribute argument type. - **Dates and times**: a `DateOnly` or `DateTime` for the year a table took effect cannot be written as a constant. - **Objects**: a `TaxReturn` with income, filing status and deductions cannot be constructed inside an attribute. - **Computed or shared rows**: rows generated from the bracket table itself, or the same rows used by several test classes, have no home in an attribute. A tempting workaround is passing strings, such as `[InlineData("40000.50")]`, into a `decimal` parameter. xUnit.net does try to convert mismatched arguments before calling the method, using `Convert.ChangeType` under the **current culture**, so the same string can be read as a different number on a build agent whose culture uses a comma as the decimal separator. Typed data sources avoid the problem. ## [MemberData]: rows from a static member - The member must be **`public static`**: a property, a field or a method. Otherwise the theory fails with "Could not find public static member (property, field, or method) named ...". - Name it with `nameof(...)` so a rename cannot silently break the link. - `MemberType = typeof(OtherClass)` reads the member from another class. - Extra constructor arguments, as in `[MemberData(nameof(RowsForYear), 2026)]`, are passed to a method; they are ignored for properties and fields. - In xunit.v3 the member may return rows as `object?[]`, as tuples or as `ITheoryDataRow` values, through `IEnumerable<T>` or `IAsyncEnumerable<T>`, optionally wrapped in `Task<T>` or `ValueTask<T>`. - A member that returns `null` fails with "Member '...' on '...' returned null when queried for test data"; a common cause is a static field copied from another static field declared below it, which is still `null` when the copy runs. ## [ClassData]: rows as a reusable class `[ClassData(typeof(JointFilerCases))]`, or the generic `[ClassData<JointFilerCases>]`, tells xUnit.net to create the class and enumerate it. The class must implement `IEnumerable<T>` or `IAsyncEnumerable<T>` of one of the supported row shapes. The simplest way to satisfy that is to derive from `TheoryData<...>` and call `Add` in the constructor. Use it when the same rows serve several test classes, or when building them needs helper methods that would clutter the test class. ## TheoryData<T> and TheoryDataRow<T> `TheoryData<T1, T2>` is a collection of typed rows with an `Add(T1, T2)` method, which makes collection-initializer syntax compile-time checked: | Data source | Where the rows live | When a wrong row is caught | |---|---|---| | `[InlineData]` | attribute arguments | when the row runs | | `[MemberData]` returning `object[]` rows | static member | when the row runs | | `[MemberData]` returning `TheoryData<...>` | static member | at compile time | | `[ClassData]` deriving from `TheoryData<...>` | separate class | at compile time | In xunit.v3, `TheoryData<T1, T2>` stores `TheoryDataRow<T1, T2>` objects and also accepts those rows directly. A row object carries per-row metadata: `Skip`, `TestDisplayName`, `Label`, `Timeout`, `Explicit` and traits, settable as properties or through `WithSkip`, `WithTestDisplayName` and `WithTrait`. For combinatorial cases, `MatrixTheoryData<T1, T2>` builds every combination of two or more value lists. ## Choosing in practice 1. Start with `[InlineData]` while every value is a constant and the table fits on screen. 2. Switch to `[MemberData]` with `TheoryData<...>` when values are `decimal`, dates or objects, or when rows are computed. 3. Move the rows into a `[ClassData]` class when a second test class needs the same table. 4. Reach for `TheoryDataRow<...>` when individual rows need their own skip reason or a readable name. ## Comparing the money Once rows are typed as `decimal`, the assertion compares them exactly: `Assert.Equal(6_000.20m, actual)` passes for `6000.2m` because `decimal` equality ignores trailing zeros. When the calculator works to more places than the table, `Assert.Equal(expected, actual, 2)` rounds **both** values to two places with `Math.Round` before comparing. `Math.Round` on a `decimal` rounds a midpoint to the nearest even digit by default, so `0.125m` becomes `0.12`, not `0.13`; tax rules that round half away from zero should be asserted with the precision applied explicitly in the expected value. ## Version note The typed-row model is xunit.v3's. In xUnit.net v2, `TheoryData<T>` was a collection of `object[]` and data members had to yield `object[]` rows; v2-style members that return `IEnumerable<object[]>` still work after an upgrade.

  • How do you pass arguments to a [MemberData] data method?
    List them after the member name: `[MemberData(nameof(RowsForYear), 2026)]` calls `public static TheoryData<decimal, decimal> RowsForYear(int year)`. Arguments are supported only for methods and are ignored for properties and fields, so one data method can serve several theories or tax years.
  • Why is TheoryData<decimal, decimal> safer than a member returning IEnumerable<object[]>?
    With `object[]` rows the compiler accepts anything: a missing value or a string where a decimal belongs surfaces only when that row runs and fails to bind. `TheoryData<decimal, decimal>` exposes `Add(decimal, decimal)`, so a malformed row in the collection initializer is a build error, and retyping a parameter shows every row that must change.

  • [MemberData] can point at a private or instance property on the test class.
  • [InlineData("40000.50")] into a decimal parameter is safe on every machine.
  • TheoryData<T> exists only for readability and adds no compile-time checking.
  • [ClassData] needs the data class to be a nested class of the test class.
  • Arguments given to [MemberData] are passed to a property's getter.

Assumes xunit.v3 4.x, where TheoryData<T> holds typed TheoryDataRow<T> rows and data members may also return tuples, ITheoryDataRow values or IAsyncEnumerable; xUnit.net v2 data members returned object[] rows.