Lesson 20 of 93 · 5 min read · Updated

MemberData in xUnit: Feeding Theories from Properties, Methods and Shared Classes

[InlineData] stops working as soon as a row needs a decimal, an object or values computed by code. [MemberData] removes that limit. It reads the rows from a static property, field or method, so the data can be any C# expression. This lesson shows the three common forms: a typed property, a method with parameters, and a data source shared across test classes.

Technical Requirements

  1. .NET 11 SDK
  2. xunit 2.9.3
  3. xunit.runner.visualstudio 4.0.1 and Microsoft.NET.Test.Sdk 18.12.0
  4. The ShippingCalculator and PasswordPolicy classes from the previous lessons

How MemberData Works

[MemberData(nameof(X))] points a theory at a static member named X on the test class. Before the test runs, xUnit reads the member and enumerates it. Each element becomes one data row, and its values are passed to the test method parameters in order.

The member can be:

  1. a static property, which is the most common form
  2. a static field
  3. a static method, which can also take arguments

Because the data comes from ordinary C# code, it can hold decimal values, records, lists or any other object. It can also build rows in a loop.

Data from a Static Property

The shipping tariff is a table: order total, weight and zone go in, a fee comes out. Each row has four values, and two of them are decimal, which [InlineData] cannot express directly.

M03.DataDriven.Tests/MemberDataTests.cs

/// <summary>Data from a static property: the most common usage.</summary>
public static TheoryData<decimal, double, ShippingZone, decimal> ShippingCases => new()
{
// orderTotal, weight, zone, expectedFee
{ 100m, 1.0, ShippingZone.Local, 30m },
{ 100m, 3.0, ShippingZone.Domestic, 70m }, // 60 + 2 * 5
{ 3_000m, 3.0, ShippingZone.Domestic, 0m }, // free shipping
{ 3_000m, 3.0, ShippingZone.International, 290m }, // no free shipping abroad
};

[Theory]
[MemberData(nameof(ShippingCases))]
public void Calculate_MatchesTariffTable(
decimal orderTotal, double weightKg, ShippingZone zone, decimal expected)
{
Assert.Equal(expected, ShippingCalculator.Calculate(orderTotal, weightKg, zone));
}

The property returns TheoryData<decimal, double, ShippingZone, decimal>. This generic type is a strongly typed list of rows. The collection initializer syntax { a, b, c, d } calls its Add method, and the compiler checks that every row has four values of the right types. If you swap two columns by mistake, the code does not compile.

Use nameof(ShippingCases) instead of the string "ShippingCases". If someone renames the property, nameof keeps the attribute in sync, and the compiler catches the change.

The last two rows sit next to each other on purpose. They use the same total and weight and differ only in the zone. Together they document the rule that free shipping does not apply abroad.

Data from a Method with Parameters

A static method can produce rows in code. It can also take arguments, which you pass after the member name in the attribute.

M03.DataDriven.Tests/MemberDataTests.cs

/// <summary>Data from a method: it can take parameters, so rows can be generated in code.</summary>
public static IEnumerable<object[]> WeightsFor(ShippingZone zone)
{
foreach (var kilos in new[] { 1.0, 2.0, 3.0, 4.0 })
{
yield return [zone, kilos];
}
}

[Theory]
[MemberData(nameof(WeightsFor), ShippingZone.Domestic)]
public void Calculate_FeeGrowsMonotonicallyWithWeight(ShippingZone zone, double weightKg)
{
var fee = ShippingCalculator.Calculate(100m, weightKg, zone);
var lighterFee = ShippingCalculator.Calculate(100m, weightKg - 0.5, zone);

// Rule: the fee does NOT decrease as the weight increases.
Assert.True(fee >= lighterFee, $"{weightKg} kg costs {fee}, the lighter parcel {lighterFee}.");
}

ShippingZone.Domestic in the attribute is passed to the zone parameter of WeightsFor. The same method could feed another theory with ShippingZone.International. The method returns IEnumerable<object[]>, the classic row shape in xUnit. Each object[] is one row.

This test does not check exact fees. It checks a rule that must hold for every weight: a heavier parcel never costs less than a lighter one. Rules like this are useful because they stay true even when the tariff values change.

The custom message in Assert.True matters. Assert.True on its own only says "Expected True, Actual False". The message tells you which weight broke the rule and what the two fees were.

Sharing Data Across Test Classes

When several test classes need the same data set, put it in its own static class and point to it with MemberType.

M03.DataDriven.Tests/MemberDataTests.cs

/// <summary>Shared data source: used from another class through MemberType.</summary>
[Theory]
[MemberData(nameof(SharedPasswordData.StrongPasswords), MemberType = typeof(SharedPasswordData))]
public void Evaluate_WithSharedData_ReturnsStrong(string password)
{
Assert.Equal(PasswordStrength.Strong, PasswordPolicy.Evaluate(password));
}

M03.DataDriven.Tests/MemberDataTests.cs

/// <summary>
/// A common data source that several test classes can use.
/// Keep helpers like this focused; do not let them become a dumping ground.
/// </summary>
public static class SharedPasswordData
{
public static TheoryData<string> StrongPasswords =>
[
"Sifre123!Guclu",
"A1b2C3d4!e5F6",
"Uzun-Parola-2026!",
];
}

MemberType = typeof(SharedPasswordData) tells xUnit to look for the member on that class instead of the test class. TheoryData<string> supports collection expressions, so the single-column rows can be written as a plain list in square brackets.

Keep shared data classes small and named after what they contain. A class called TestData with fifty unrelated members becomes hard to change, because nobody knows which tests depend on which rows.

Pitfall: Data Must Be Deterministic

The data a member returns must be the same every time it runs. Do not use Random, DateTime.Now or Guid.NewGuid() to build rows. If a randomly generated row fails, you cannot reproduce the failure, because the next run produces different data. Test Explorer can also lose track of test cases whose arguments change between discovery and execution.

If you want generated inputs, generate them from fixed values, as WeightsFor does, or use a fixed seed. Property-based testing, covered later in this section, is the right tool when you want many random inputs.

Summary

  1. [MemberData] reads theory rows from a static property, field or method.
  2. Return TheoryData<T1, T2, ...> for strongly typed rows that the compiler checks.
  3. Use nameof for the member name and pass method arguments after it in the attribute.
  4. Use MemberType = typeof(X) to share a focused data set across test classes.
  5. Keep member data deterministic, so every failure can be reproduced.