skip to content

Attributes & Data Rows

[TestClass], [TestMethod], [DataRow] and [DynamicData] declare MSTest tests, wrapped by static class and assembly hooks. Interviewers ask why [ExpectedException] gave way to Assert.ThrowsExactly.

on this pageshow

explore

questions

6

In MSTest 4, how do [TestClass], [TestMethod] and [DataRow] turn one method into several test cases?

level: juniorimportance: must knowfreq 70%

answer

  1. discovery needs two attributes
  2. one result per row by default
  3. row arguments match the parameters
  4. DisplayName and IgnoreMessage per row
  5. MSTEST0014 checks each row

basics

~20 s

[TestClass] marks a public class whose public [TestMethod] methods MSTest discovers. Each [DataRow] on a test method supplies one argument list, and MSTest runs the method once per row as a separate test case with its own result.

solid answer

~40 s

MSTest only discovers a `[TestMethod]` inside a class marked `[TestClass]`; both must be `public` (or `internal` with `[assembly: DiscoverInternals]`), and the method must be non-static and return `void`, `Task` or `ValueTask` — never `async void`. Stacking `[DataRow(...)]` attributes on the method makes it parameterised: each row is one argument list whose count and types must match the parameters, and by default each row becomes its own test case with its own instance, its own `[TestInitialize]`/`[TestCleanup]` pass and its own outcome. For a password-strength checker that is `[DataRow("abc", PasswordStrength.Weak)]`, `[DataRow("Tr0ub4dor&3x!", PasswordStrength.Strong)]` and so on above one method. A row can carry its own `DisplayName` or an `IgnoreMessage` that skips just that row, and analyzer MSTEST0014 warns when a row does not fit the signature. `[DataTestMethod]` is no longer needed.

code

csharp · 21 lines
csharp
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public sealed class PasswordStrengthCheckerTests
{
    private readonly PasswordStrengthChecker _checker = new();

    [TestMethod]
    [DataRow("abc", PasswordStrength.Weak)]
    [DataRow("password123", PasswordStrength.Weak, DisplayName = "Common password")]
    [DataRow("Summer2026", PasswordStrength.Medium)]
    [DataRow("Tr0ub4dor&3x!", PasswordStrength.Strong)]
    [DataRow("correct horse battery staple", PasswordStrength.Strong,
        IgnoreMessage = "Passphrase rule not shipped yet")]
    public void Evaluate_ReturnsExpectedStrength(string password, PasswordStrength expected)
    {
        PasswordStrength actual = _checker.Evaluate(password);

        Assert.AreEqual(expected, actual);
    }
}

go deeper

for a junior

Recall the trio: [TestClass] on a public class, [TestMethod] on public instance methods, one [DataRow] per input set with parameters that match it, and Assert.AreEqual(expected, actual) in the body.

for a middle

Explain that each row unfolds into its own test case with its own instance and TestInitialize/TestCleanup pass, why rows are limited to compile-time constants, and where DisplayName and IgnoreMessage help.

for a senior

Show you keep data-driven suites readable at scale: analyzers such as MSTEST0014 and MSTEST0030 as warnings, display names that explain intent, and moving non-constant or bulky data to DynamicData.

for a principal

Weigh inline rows against shared data sources for a team: rows keep the case next to the assertion, while sources reduce duplication but hide the inputs from a reviewer reading the test.

## The two discovery attributes MSTest finds tests by reflection over the compiled test assembly. Two attributes from the `Microsoft.VisualStudio.TestTools.UnitTesting` namespace drive that discovery: - **`[TestClass]`** marks a class as a container of tests. Only types carrying it are scanned. - **`[TestMethod]`** marks a method inside such a class as a test. Both have layout rules, which the analyzers MSTEST0002 (test class) and MSTEST0003 (test method) check at build time: 1. The class and the method are `public`, or `internal` when the assembly carries `[assembly: DiscoverInternals]`. 2. The test method is an instance method: not `static`, not `abstract`. 3. It returns `void`, `Task` or `ValueTask`. An `async void` test is invalid, because MSTest would have nothing to await. 4. A generic test method is allowed when the type arguments can be inferred from the data. A method with `[TestMethod]` in a class without `[TestClass]` is simply never run; since MSTest 4.0 analyzer MSTEST0030 raises that as a **warning**, so the mistake shows up in the build output rather than as a silently shrinking test count. ## One method, many cases with `[DataRow]` A **parameterised test** is one method that runs against many inputs. In MSTest the simplest source of inputs is **`[DataRow]`**: each attribute holds one argument list, and the method receives those values through its parameters. The reserved scenario here is a `PasswordStrengthChecker` whose `Evaluate(string)` method returns a `PasswordStrength` value; the rows list passwords next to the strength each should earn. With default settings every row is **unfolded** into a separate test case. That has concrete consequences: - each row appears as its own entry in Test Explorer, the console output and the TRX report; - one failing row does not hide the others — four rows give four results; - the per-test lifecycle runs once per row: a fresh instance of the class, `[TestInitialize]` before, `[TestCleanup]` after. The opposite behaviour, **folding** all rows into one test case, exists as an opt-in: `[TestMethod(UnfoldingStrategy = TestDataSourceUnfoldingStrategy.Fold)]`. It is rarely what you want for a handful of inline rows. ## What a row may contain `DataRowAttribute` takes `object?` arguments, so the C# compiler cannot check them against the method's parameters. The constraint it does enforce is the language's own: attribute arguments must be compile-time constants. | Fits in a `[DataRow]` | Does not fit | |---|---| | string, `int`, `bool`, `double` and other primitive literals | a `decimal` literal or a `DateTime` value | | enum members such as `PasswordStrength.Weak` | an object created with `new` | | `null` | data computed at run time or read from a file | | arrays of constants, `params` arrays | hundreds of generated rows | When the data does not fit, the next tool is `[DynamicData]`, which reads rows from a static member instead of from attribute arguments. Because the compiler cannot match a row to the signature, analyzer **MSTEST0014** does: it warns when a row's argument count or types do not fit the parameters. **MSTEST0042** warns about duplicate rows that would run the same case twice. ## Per-row metadata and skipping `DataRowAttribute` has two named properties beside its data: - **`DisplayName`** replaces the generated case name (method name plus argument values) in reports — useful when a raw password string says little about why the row exists. - **`IgnoreMessage`** skips only that row and records the reason; the other rows keep running. To skip every case of a method, or a whole class, put **`[Ignore]`** (optionally with a reason string) on the method or the class instead. MSTest reports ignored tests as skipped, not as passed. ## Legacy names you will still meet - **`[DataTestMethod]`** derives from `TestMethodAttribute` and adds nothing. The framework hides it from IntelliSense and documents it as present only for backward compatibility; plain `[TestMethod]` handles data rows. - **`[TestMethod("Readable name")]`** was the MSTest 3 way to set a display name. In MSTest 4 the constructor's parameters are caller-info values, so the name moves to `[TestMethod(DisplayName = "Readable name")]`. ## The shape to remember A parameterised MSTest 4 test is a `[TestClass]` holding a `[TestMethod]` with one `[DataRow]` per case, parameters typed to match the rows, and `Assert.AreEqual(expected, actual)` in the body. Everything else — dynamic sources, folding, per-row metadata — is a variation on that shape.

  • Why is [DataTestMethod] no longer needed in MSTest 4?
    `DataTestMethodAttribute` derives from `TestMethodAttribute` and adds no behaviour; MSTest marks it hidden from IntelliSense and keeps it only for backward compatibility. A plain `[TestMethod]` already expands every `[DataRow]` into its own case, so new tests use `[TestMethod]` alone and old ones can be switched without any change in results.
  • What happens when a [DataRow] passes a string where the parameter is an int?
    It compiles, because `DataRow` takes `object?` arguments. Analyzer MSTEST0014 warns at build time that the row does not match the signature. If the warning is ignored, that row fails when MSTest invokes the method with an argument of the wrong type, while the other rows still run and report on their own.
  • How do you skip a whole MSTest test class while a bug is being fixed?
    Put `[Ignore("reason")]` on the class; `IgnoreAttribute` targets classes as well as methods. Every test in it is reported as skipped with the reason, which keeps the gap visible in reports, unlike deleting or commenting the tests out. Analyzer MSTEST0066 suggests giving each ignore a justification, and MSTEST0015, off by default, can flag ignored tests altogether.

  • A [TestMethod] runs even when its class has no [TestClass] attribute.
  • Parameterised MSTest tests need [DataTestMethod] instead of [TestMethod].
  • By default all [DataRow] cases share one result, so one failure hides the rest.
  • [TestInitialize] runs once per method, not once for each data row.
  • A [DataRow] can take a new PasswordPolicy(...) object as an argument.
  • [TestMethod("Readable name")] still sets the display name in MSTest 4.

Assumes MSTest 4.4.1: [TestMethod] takes a display name only as DisplayName = since v4, and [DataTestMethod] remains solely for backward compatibility.

open as a page

In MSTest 4, why did [ExpectedException] give way to Assert.Throws and Assert.ThrowsExactly, and how do the two differ?

level: middleimportance: must knowfreq 58%

basics

~20 s

[ExpectedException] passed when any line of the test threw, so it could hide bugs, and MSTest 4 removed it. Assert.Throws<T> wraps only the call under test and accepts T or a subclass; Assert.ThrowsExactly<T> requires exactly T. Both return the exception.

open as a page

In MSTest 4, when do you choose [DynamicData] over [DataRow], and how does it locate and shape its rows?

level: middleimportance: should knowfreq 42%

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.

open as a page

In MSTest 4, in what order do the assembly, class and test lifecycle hooks run, and what signatures must they have?

level: middleimportance: should knowfreq 55%

basics

~20 s

[AssemblyInitialize] runs once, [ClassInitialize] once per class, then for each test: constructor, [TestInitialize], the test, [TestCleanup], Dispose; [ClassCleanup] and [AssemblyCleanup] close out. Assembly and class hooks are public static, and both initializers take one TestContext.

open as a page

Upgrading a test project from MSTest 3 to MSTest 4, which attribute, Assert and TestContext changes break the build or quietly change behaviour?

level: seniorimportance: should knowfreq 32%

basics

~10 s

MSTest 4 removes [ExpectedException], Assert.ThrowsException, ClassCleanupBehavior and TestTimeout, retypes TestContext.Properties, and silently changes [TestMethod("name")], class-cleanup timing and TestContext reads in initializers. It is not binary compatible, so everything built on 3 is recompiled.

open as a page

An MSTest 4 test marked [Timeout(2000)] is reported as timed out, yet its work keeps running and breaks the next test; what is happening and how do you fix it?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

By default MSTest's [Timeout] reports the timeout and abandons the test's task, which keeps running in the background. Set CooperativeCancellation = true and pass TestContext.CancellationToken into the work so the test actually stops before the next one starts.

open as a page