Lesson 21 of 93 · 5 min read · Updated
ClassData and TheoryData in xUnit: Scaling Test Data with Type Safety
On this page
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
- .NET 11 SDK
- xunit 2.9.3
- xunit.runner.visualstudio 4.0.1 and Microsoft.NET.Test.Sdk 18.12.0
- The
PasswordPolicyclass 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
M03.DataDriven.Tests/ClassDataAndTheoryDataTests.cs
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
M03.DataDriven.Tests/ClassDataAndTheoryDataTests.cs
The test method looks the same, and the attribute is the same. The difference is in the data class:
Add("abc", PasswordStrength.Weak)is checked by the compiler. Swapping the arguments or passing anintinstead of aPasswordStrengthis a build error.- There is no
GetEnumeratorcode to write. - 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.
| Need | Use |
|---|---|
| 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
[ClassData(typeof(X))]reads theory rows from a separate class that xUnit creates and enumerates.- The classic
IEnumerable<object[]>form has no type safety: wrong types or column order fail only at run time. - Deriving from
TheoryData<T1, T2, ...>gives compile-time checks and removes the enumeration boilerplate. TheoryDataworks with both[MemberData]and[ClassData], so data can move between them easily.- Use
[ClassData]only when the data set is large or reused; keep small sets next to the test.