Lesson 21 of 93 · 5 min read · Updated

ClassData and TheoryData in xUnit: Scaling Test Data with Type Safety

When a data set grows large or gets reused, it deserves its own class. [ClassData] lets a theory read its rows from a separate class, and TheoryData<T...> makes those rows strongly typed. This lesson compares the classic IEnumerable<object[]> approach with a class that derives from TheoryData, and explains why the typed version should be your default.

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 PasswordPolicy class from the previous lessons

The Rules Being Tested

PasswordPolicy.Evaluate returns Weak for anything shorter than eight characters. For longer passwords it adds one point each for a lower-case letter, an upper-case letter, a digit, a symbol and a length of twelve or more. Five points give Strong, three or four give Medium, and fewer give Weak.

Several scoring branches and two length limits mean many meaningful scenarios. That is the kind of data set that can outgrow a list of attributes above a test method.

Classic ClassData: IEnumerable of object[]

[ClassData(typeof(X))] tells xUnit to create an instance of X and enumerate it. In its classic form, X implements IEnumerable<object[]>, and each array is one row.

M03.DataDriven.Tests/ClassDataAndTheoryDataTests.cs

/// <summary>
/// Classic ClassData: returns object[]. Flexible, but there is no type safety:
/// you notice a parameter in the wrong order only at RUN TIME.
/// </summary>
public sealed class PasswordScenarios : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
// Write descriptive scenarios, not a pile of meaningless data.
yield return ["parolaparola", PasswordStrength.Weak]; // lower case only
yield return ["Parola12", PasswordStrength.Medium]; // upper + lower + digit
yield return ["Parola12!Uzun", PasswordStrength.Strong]; // everything + length
}

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

M03.DataDriven.Tests/ClassDataAndTheoryDataTests.cs

[Theory]
[ClassData(typeof(PasswordScenarios))]
public void Evaluate_WithClassData_ReturnsExpectedStrength(
string password, PasswordStrength expected)
{
Assert.Equal(expected, PasswordPolicy.Evaluate(password));
}

This works, and you will see it in many existing code bases. The weakness is the object[]. The compiler accepts anything in the array. If you write [PasswordStrength.Weak, "parolaparola"] with the columns swapped, or add a third value by mistake, the project still builds. The error appears only when the test runs and xUnit fails to bind the arguments. You also need the non-generic GetEnumerator boilerplate at the bottom of the class.

Note the comments on each row. The first password is twelve characters long, so it scores a point for length and a point for lower-case letters. Two points are still Weak. Without the comment, a reader might think the row is wrong.

Typed ClassData: Deriving from TheoryData

TheoryData<T1, T2> is an xUnit class that already implements the enumeration for you. Each call to Add creates one row, and the generic parameters fix the type of every column. Derive from it and add the rows in the constructor.

M03.DataDriven.Tests/ClassDataAndTheoryDataTests.cs

/// <summary>
/// The preferred way: a ClassData that derives from TheoryData.
/// It gives you the structure of a separate class and type safety together.
/// </summary>
public sealed class TypedPasswordScenarios : TheoryData<string, PasswordStrength>
{
public TypedPasswordScenarios()
{
Add("abc", PasswordStrength.Weak);
Add("Abcdefg1", PasswordStrength.Medium);
Add("Abcdefg1!xyz", PasswordStrength.Strong);
}
}

M03.DataDriven.Tests/ClassDataAndTheoryDataTests.cs

[Theory]
[ClassData(typeof(TypedPasswordScenarios))]
public void Evaluate_WithTypedClassData_ReturnsExpectedStrength(
string password, PasswordStrength expected)
{
Assert.Equal(expected, PasswordPolicy.Evaluate(password));
}

The test method looks the same, and the attribute is the same. The difference is in the data class:

  1. Add("abc", PasswordStrength.Weak) is checked by the compiler. Swapping the arguments or passing an int instead of a PasswordStrength is a build error.
  2. There is no GetEnumerator code to write.
  3. The class signature, TheoryData<string, PasswordStrength>, documents the shape of every row at a glance.

The xUnit analyzers also benefit. When the data source is typed, they can compare its type arguments with the test method parameters and warn you about a mismatch while you type.

The typed rows here also sit right on the boundaries. Abcdefg1 is exactly eight characters, the shortest password that is not weak by length. Abcdefg1!xyz is exactly twelve characters, the shortest one that earns the length point.

TheoryData with MemberData

TheoryData is not only for [ClassData]. The previous lesson used it as the return type of a static property for [MemberData]. The same type works in both places, so you can start with a property next to the test and move it into its own class later without changing the row format.

Choosing a Data Source

Each data attribute fits a different size and reuse level. Pick the smallest one that does the job.

NeedUse
2 to 5 simple rows that should stay next to the test[InlineData]
Complex objects or rows produced by code[MemberData]
A data set shared by several test classes[MemberData(..., MemberType = typeof(X))]
A large set that deserves its own class[ClassData] with a class derived from TheoryData<T...>

A common mistake is reaching for [ClassData] too early. A separate class adds a jump for the reader: to understand the test, they must open another file. Three short rows are easier to read as [InlineData] attributes. Move to [ClassData] when the data set is large, has its own setup logic, or is used by more than one test.

Whatever the source, write rows that each represent one scenario with a clear purpose. A data class with forty random-looking rows tells nobody which rules are covered. Fewer rows, each on a boundary or a distinct branch, give better coverage and are easier to maintain.

Summary

  1. [ClassData(typeof(X))] reads theory rows from a separate class that xUnit creates and enumerates.
  2. The classic IEnumerable<object[]> form has no type safety: wrong types or column order fail only at run time.
  3. Deriving from TheoryData<T1, T2, ...> gives compile-time checks and removes the enumeration boilerplate.
  4. TheoryData works with both [MemberData] and [ClassData], so data can move between them easily.
  5. Use [ClassData] only when the data set is large or reused; keep small sets next to the test.