skip to content

With xunit.v3, why does a theory fed TaxReturn objects through [MemberData] show up as one test case instead of one per row, and how do you fix it?

level: seniorimportance: nice to knowfreq 26%

answer

  1. discovery versus execution
  2. rows are pre-enumerated at discovery
  3. every argument must serialize
  4. IXunitSerializable needs a parameterless constructor
  5. DisableDiscoveryEnumeration = true

basics

~20 s

xunit.v3 lists a test case per theory row only when discovery pre-enumerates the data and can serialize every argument. A plain TaxReturn class is not serializable, so the theory collapses to one case. Pass serializable values, or implement IXunitSerializable.

solid answer

~50 s

To list each row as a separately runnable test, discovery must enumerate the data and serialize every resolved argument, because the serialized arguments become part of the test case's identity. The built-in serializers cover primitives, `string`, `decimal`, the date and time types, `Guid`, `Uri`, `Version`, enums and arrays of those; an ordinary `TaxReturn` class is not covered, so xunit.v3 sends the diagnostic message "Non-serializable data ... falling back to single test case" and reports the theory as one case whose rows appear only when it runs. You can no longer run or rerun one failing row by itself. Fixes, in order: feed the theory serializable values and build the `TaxReturn` inside the test; implement `IXunitSerializable` with a public parameterless constructor; or write an `IXunitSerializer` and register it with `[assembly: RegisterXunitSerializer(...)]`. For random, time-based or expensive data, set `DisableDiscoveryEnumeration = true` deliberately.

code

csharp · 25 lines
csharp
using Xunit.Sdk;

public sealed class TaxReturn : IXunitSerializable
{
    public TaxReturn() { }                     // needed to deserialize
    public TaxReturn(decimal income, FilingStatus status) =>
        (Income, Status) = (income, status);

    public decimal Income { get; private set; }
    public FilingStatus Status { get; private set; }

    public void Serialize(IXunitSerializationInfo info)
    {
        info.AddValue(nameof(Income), Income);
        info.AddValue(nameof(Status), Status);
    }

    public void Deserialize(IXunitSerializationInfo info)
    {
        Income = info.GetValue<decimal>(nameof(Income));
        Status = info.GetValue<FilingStatus>(nameof(Status));
    }

    public override string ToString() => $"{Status} {Income:N0}";
}

go deeper

for a junior

Know that theory rows can be listed individually only when their values are simple, serializable types.

for a middle

Explain discovery versus execution, the serializable built-ins, and why an object argument collapses the theory into one test case.

for a senior

Diagnose the single-node theory from its symptoms, pick the cheapest fix (primitive rows, IXunitSerializable or a registered serializer), and use DisableDiscoveryEnumeration deliberately.

for a principal

Decide how much per-row selectability a large suite needs in CI and IDEs, and set data-shape conventions that keep theories rerunnable row by row.

## Discovery versus execution An xUnit.net run has two phases. **Discovery** finds the tests and produces a list of test cases, each with a unique ID; IDEs build their test tree from it and runners use the IDs to run a chosen subset. **Execution** then runs the selected cases. For a theory the question is whether each data row becomes its own discovered test case, or whether the whole theory is one case that expands into rows only when it executes. Rows become individual cases only when discovery **pre-enumerates** the theory data. In xunit.v3 4.x that is off by default in the core framework and is decided by the runner: the Microsoft.Testing.Platform integration switches it on, so that listing tests shows individual rows, and the `preEnumerateTheories` setting in `xunit.runner.json` sets it explicitly. ## When a row becomes its own test case With pre-enumeration on, xunit.v3 still falls back to a single case for the whole theory unless all of these hold: 1. Neither `[Theory]` nor the data attribute sets `DisableDiscoveryEnumeration = true`. 2. Every data attribute supports enumeration at discovery time. 3. Enumerating the data does not hand xUnit.net disposable objects to track. 4. **Every resolved argument in every row is serializable**, because the serialized arguments are what let a runner recreate exactly that row later from its ID. The fallback is quiet: it is reported only as a diagnostic message that starts "Non-serializable data" and ends "falling back to single test case." Diagnostic messages are hidden unless enabled, so most teams see only the symptom. ## What counts as serializable | Category | Examples | |---|---| | built-in values | `string`, `char`, all integer types, `float`, `double`, `decimal`, `bool` | | dates and identifiers | `DateTime`, `DateTimeOffset`, `DateOnly`, `TimeOnly`, `TimeSpan`, `Guid`, `Uri`, `Version`, `BigInteger` | | other | enums, `Type`, arrays of supported values, nullable forms | | opt-in | types implementing `IXunitSerializable`, types handled by a registered `IXunitSerializer` | A record or class such as `TaxReturn(decimal Income, FilingStatus Status)` is not on the list just because its properties are. ## Symptoms of the fallback - The IDE shows the theory as one node; its rows appear only after a run. - A single failing row cannot be rerun alone; the whole theory runs every time. - Listing tests by ID shows one entry for the theory. - All rows still execute and are reported individually after the run, so nothing is lost silently except selectability. - Rerun-failed-tests features in IDEs and CI, which rely on stable test IDs, rerun the entire theory rather than the one broken bracket. ## Fixes 1. **Feed primitives, build objects in the test.** Make the row `(decimal income, FilingStatus status, decimal expected)` and construct the `TaxReturn` inside the method. This is the simplest fix and keeps data readable in the report. 2. **Implement `IXunitSerializable`** (namespace `Xunit.Sdk`) on the type: `Serialize` stores each field with `info.AddValue(...)`, `Deserialize` reads them back with `info.GetValue<T>(...)`, and the type needs a public parameterless constructor so xUnit.net can create an empty instance to fill. 3. **Register an `IXunitSerializer`** for types you cannot change, with `[assembly: RegisterXunitSerializer(typeof(TaxReturnSerializer), typeof(TaxReturn))]`. The serializer implements three members: `IsSerializable`, which can refuse a particular value with a reason, `Serialize`, which turns the value into a string, and `Deserialize`, which rebuilds it from that string. Registering it at assembly level means every theory in the project can take that type. 4. **Opt out on purpose** with `DisableDiscoveryEnumeration = true` when the data is random, time-dependent or expensive to compute, accepting a single case in exchange for not computing rows during discovery. ## A related failure Static field initialisers run in textual order, so `public static TheoryData<decimal, decimal> Rows = Source;` declared above `Source` copies `null`. The `[MemberData]` lookup then fails with "Member 'Rows' on 'TaxTests' returned null when queried for test data" instead of producing rows. Returning a new `TheoryData<...>` from an expression-bodied property avoids the ordering problem, because the rows are built on every read.

  • Does overriding ToString on TaxReturn make each row its own test case?
    No. `ToString` only changes how the argument is printed in the display name. Identity comes from serialization, so a non-serializable type still collapses the theory to one case. Use `ToString` together with `IXunitSerializable`, or switch the row to serializable values.
  • When is DisableDiscoveryEnumeration = true the right choice?
    When rows should not be computed during discovery: random values, data that depends on the clock, rows read from a slow source, or objects that need disposal. You accept a single test case that expands at run time, and lose the ability to select one row, in exchange for cheap and stable discovery.

  • xunit.v3 serializes any theory argument with System.Text.Json.
  • Overriding ToString() on TaxReturn makes each row a separate test case.
  • A theory collapsed to one test case runs only its first data row.
  • Implementing IXunitSerializable works even without a parameterless constructor.
  • DisableDiscoveryEnumeration speeds up every theory at no cost.

Assumes xunit.v3 4.x: pre-enumeration is off in the core framework unless a runner or xunit.runner.json enables it, and the Microsoft.Testing.Platform integration enables it by default.