In MSTest 4, when do you choose [DynamicData] over [DataRow], and how does it locate and shape its rows?
answer
- attribute arguments must be constants
- public static member named by nameof
- DynamicDataSourceType.AutoDetect
- ValueTuple or TestDataRow<T> items
- MSTEST0018 validates the source
basics
~20 s[DynamicData] fits when rows are not compile-time constants, are computed, or are too many to inline. It names a public static method, property or field returning an IEnumerable of tuples, object[] or TestDataRow<T>, and each item becomes one test case.
solid answer
~40 sC# attribute arguments must be constants, so `[DataRow]` cannot carry a `DateTime`, a `decimal`, an object or a few hundred rows read from a file. `[DynamicData(nameof(BoundaryPasswords))]` instead names a `public static` method, property or field; MSTest 4 auto-detects which (`DynamicDataSourceType.AutoDetect`), so the old source-type argument is unnecessary and MSTEST0052 discourages it. The member returns an `IEnumerable<T>` of `ValueTuple`s, `Tuple`s, `object[]` or `TestDataRow<T>`, and each item becomes one case. A `Type` argument reads the member from another class, and extra constructor arguments are passed to a source method's parameters. `TestDataRow<T>` adds per-row `DisplayName`, `IgnoreMessage` and `TestCategories`, while the attribute's own `IgnoreMessage` skips every row. MSTEST0018 warns when the source is missing, not static or the wrong shape.
code
csharp · 22 lines[TestClass]
public sealed class PasswordBoundaryTests
{
public static IEnumerable<TestDataRow<(string Password, PasswordStrength Expected)>> BoundaryPasswords()
{
yield return new(("Ab1!", PasswordStrength.Weak)) { DisplayName = "4 chars, all classes" };
yield return new((new string('a', 13) + "1", PasswordStrength.Medium))
{
DisplayName = "14 chars, 2 classes"
};
yield return new((new string('x', 129), PasswordStrength.Weak))
{
DisplayName = "Over max length",
IgnoreMessage = "Max-length rule pending"
};
}
[TestMethod]
[DynamicData(nameof(BoundaryPasswords))]
public void Evaluate_AtBoundaries(string password, PasswordStrength expected)
=> Assert.AreEqual(expected, new PasswordStrengthChecker().Evaluate(password));
}go deeper
Remember the rule of thumb: constants go in DataRow, anything built by code goes in a public static member referenced by DynamicData with nameof.
Explain the constant-argument limit, how AutoDetect finds a method, property or field, the supported return shapes, and what TestDataRow<T> adds per row.
Show judgement about shared corpora: typed tuples over object[], analyzers MSTEST0018 and MSTEST0052 as guards, and folding very large sources so reports stay readable.
Decide where test data lives for a team: inline rows aid review, shared sources reduce duplication, and generated corpora need ownership so nobody edits expectations blindly.
## Why `[DataRow]` runs out `[DataRow]` stores test inputs as **attribute arguments**, and C# allows only compile-time constants there: literals, enum members, `typeof`, `null` and arrays of those. That rules out several inputs a password-strength checker needs: - a `decimal`, `DateTime` or `TimeSpan` value (for example a password-age policy); - an object such as a `PasswordPolicy` configured with a minimum length and required character classes; - rows computed by code — every length from 1 to 128, or each character class removed in turn; - a list of a few hundred known-breached passwords loaded from a file. **`[DynamicData]`** moves the rows out of the attribute and into an ordinary static member, where any C# expression is allowed. ## How `[DynamicData]` finds its source The attribute takes the **name** of the source member, normally written with `nameof` so a rename cannot break it silently. The member must be `public static` and can be: 1. a **method** — the natural choice for `yield return` and computed data; 2. a **property** — concise for a fixed collection; 3. a **field** — supported since MSTest 3.11. MSTest 4 resolves which kind it is by itself: the constructors without a source-type argument use `DynamicDataSourceType.AutoDetect`. Passing `DynamicDataSourceType.Method` or `.Property` explicitly still compiles, but analyzer **MSTEST0052** warns against it. Two further constructor arguments are useful: - a **`Type`** — `[DynamicData(nameof(PasswordCorpus.Breached), typeof(PasswordCorpus))]` reads the member from another class, which lets several test classes share one corpus; - **trailing `params` values** — passed as arguments to a source *method*, so one method can produce variants, for example `[DynamicData(nameof(PasswordsOfLength), 8)]`. Analyzer **MSTEST0018** checks at build time that the member exists, is accessible and static, and returns a supported type. ## Shapes a source may return The member returns any `IEnumerable<T>` — an array, a `List<T>` or an iterator. What `T` is decides how much the compiler checks: | Item type | Type checking | Per-row metadata | Typical use | |---|---|---|---| | `ValueTuple`, e.g. `(string, PasswordStrength)` | compile time | no | most new tests | | `Tuple<...>` | compile time | no | where `ValueTuple` cannot be used | | `TestDataRow<T>` | compile time | yes | rows needing names, categories or a skip | | `object[]` | run time only | no | older code | The tuple's elements are spread across the method's parameters in order, so `(string Password, PasswordStrength Expected)` feeds `Evaluate_AtBoundaries(string password, PasswordStrength expected)`. ## Per-row metadata with `TestDataRow<T>` `TestDataRow<T>` wraps one row's value and adds three settable properties: - **`DisplayName`** — a readable case name instead of the argument dump; - **`IgnoreMessage`** — skips just this row with a reason; - **`TestCategories`** — categories for this row only. On the attribute itself, **`IgnoreMessage`** skips every row the source yields, and **`DynamicDataDisplayName`** names a `public static string` method taking a `MethodInfo` and an `object[]` that formats every case's name. For per-row names, `TestDataRow<T>` is the simpler route. ## Unfolding: one case per item By default MSTest **unfolds** a data source: each item becomes a separate test case, with its own instance, lifecycle hooks and result. Since MSTest 4 the switch lives on the test method attribute — `[TestMethod(UnfoldingStrategy = TestDataSourceUnfoldingStrategy.Fold)]` reports all items as one case — rather than on `[DataRow]` or `[DynamicData]`, where MSTest 3.7 first put it. Folding is worth considering for very large generated sources where hundreds of entries would flood a report. ## Picking between the data attributes - **`[DataRow]`** — a few constant cases you want visible right above the method. - **`[DynamicData]`** — non-constant, computed, shared or bulky data. - **`[CombinatorialData]`** (namespace `Microsoft.VisualStudio.TestTools.UnitTesting.Combinatorial`, new in MSTest 4.4) — the full Cartesian product of independent parameter values. - **A custom attribute implementing `ITestDataSource`** — when the rows come from somewhere none of these reach; it implements `GetData(MethodInfo)` returning `IEnumerable<object?[]>` and `GetDisplayName`. All of them work with a **generic** test method too: since MSTest 3.8 the type arguments are inferred from the row values, so one `Evaluate_RoundTrips<T>(T value)` can take both string and enum rows. `[DataSource]`, which reads CSV or database rows, exists only on .NET Framework; a .NET 10 test project uses `[DynamicData]` for the same job.
- How do you feed a parameter to a [DynamicData] source method?Pass the values after the member name: `[DynamicData(nameof(PasswordsOfLength), 8)]` uses the constructor's trailing `params object?[]`, and MSTest calls `PasswordsOfLength(8)` to get the rows. There is a matching overload that also takes the declaring `Type`. The values are still attribute arguments, so they must be constants themselves.
- Why is object[] the weakest return shape for a [DynamicData] source?With `IEnumerable<object[]>` nothing ties an element's type or position to the method's parameters, so a swapped or mistyped value compiles and only fails when the row runs. `ValueTuple` and `TestDataRow<T>` items are typed, so the compiler and MSTEST0018 can catch a mismatch before the run.
- A [DynamicData] source member can be an instance method of the test class.
- MSTest 4 still requires DynamicDataSourceType.Method or .Property on every [DynamicData].
- [DataRow] can hold a decimal literal or a new PasswordPolicy() just like an int.
- All rows from one [DynamicData] source always report as a single test result.
- The [DataSource] attribute is the way to read CSV rows in a .NET 10 test project.
Assumes MSTest 4.4.1: DynamicData auto-detects method, property or field sources (fields since 3.11), and the unfolding strategy moved to TestMethodAttribute in v4.