1
---
2
name: csharp-mstest
3
description: 'Get best practices for MSTest 3.x/4.x unit testing, including modern assertion APIs and data-driven tests'
4
---
5
6
# MSTest Best Practices (MSTest 3.x/4.x)
7
8
Your goal is to help me write effective unit tests with modern MSTest, using current APIs and best practices.
9
10
## Project Setup
11
12
- Use a separate test project with naming convention `[ProjectName].Tests`
13
- Reference MSTest 3.x+ NuGet packages (includes analyzers)
14
- Consider using MSTest.Sdk for simplified project setup
15
- Run tests with `dotnet test`
16
17
## Test Class Structure
18
19
- Use `[TestClass]` attribute for test classes
20
- **Seal test classes by default** for performance and design clarity
21
- Use `[TestMethod]` for test methods (prefer over `[DataTestMethod]`)
22
- Follow Arrange-Act-Assert (AAA) pattern
23
- Name tests using pattern `MethodName_Scenario_ExpectedBehavior`
24
25
```csharp
26
[TestClass]
27
public sealed class CalculatorTests
28
{
29
[TestMethod]
30
public void Add_TwoPositiveNumbers_ReturnsSum()
31
{
32
// Arrange
33
var calculator = new Calculator();
34
35
// Act
36
var result = calculator.Add(2, 3);
37
38
// Assert
39
Assert.AreEqual(5, result);
40
}
41
}
42
```
43
44
## Test Lifecycle
45
46
- **Prefer constructors over `[TestInitialize]`** - enables `readonly` fields and follows standard C# patterns
47
- Use `[TestCleanup]` for cleanup that must run even if test fails
48
- Combine constructor with async `[TestInitialize]` when async setup is needed
49
50
```csharp
51
[TestClass]
52
public sealed class ServiceTests
53
{
54
private readonly MyService _service; // readonly enabled by constructor
55
56
public ServiceTests()
57
{
58
_service = new MyService();
59
}
60
61
[TestInitialize]
62
public async Task InitAsync()
63
{
64
// Use for async initialization only
65
await _service.WarmupAsync();
66
}
67
68
[TestCleanup]
69
public void Cleanup() => _service.Reset();
70
}
71
```
72
73
### Execution Order
74
75
1. **Assembly Initialization** - `[AssemblyInitialize]` (once per test assembly)
76
2. **Class Initialization** - `[ClassInitialize]` (once per test class)
77
3. **Test Initialization** (for every test method):
78
1. Constructor
79
2. Set `TestContext` property
80
3. `[TestInitialize]`
81
4. **Test Execution** - test method runs
82
5. **Test Cleanup** (for every test method):
83
1. `[TestCleanup]`
84
2. `DisposeAsync` (if implemented)
85
3. `Dispose` (if implemented)
86
6. **Class Cleanup** - `[ClassCleanup]` (once per test class)
87
7. **Assembly Cleanup** - `[AssemblyCleanup]` (once per test assembly)
88
89
## Modern Assertion APIs
90
91
MSTest provides three assertion classes: `Assert`, `StringAssert`, and `CollectionAssert`.
92
93
### Assert Class - Core Assertions
94
95
```csharp
96
// Equality
97
Assert.AreEqual(expected, actual);
98
Assert.AreNotEqual(notExpected, actual);
99
Assert.AreSame(expectedObject, actualObject); // Reference equality
100
Assert.AreNotSame(notExpectedObject, actualObject);
101
102
// Null checks
103
Assert.IsNull(value);
104
Assert.IsNotNull(value);
105
106
// Boolean
107
Assert.IsTrue(condition);
108
Assert.IsFalse(condition);
109
110
// Fail/Inconclusive
111
Assert.Fail("Test failed due to...");
112
Assert.Inconclusive("Test cannot be completed because...");
113
```
114
115
### Exception Testing (Prefer over `[ExpectedException]`)
116
117
```csharp
118
// Assert.Throws - matches TException or derived types
119
var ex = Assert.Throws<ArgumentException>(() => Method(null));
120
Assert.AreEqual("Value cannot be null.", ex.Message);
121
122
// Assert.ThrowsExactly - matches exact type only
123
var ex = Assert.ThrowsExactly<InvalidOperationException>(() => Method());
124
125
// Async versions
126
var ex = await Assert.ThrowsAsync<HttpRequestException>(async () => await client.GetAsync(url));
127
var ex = await Assert.ThrowsExactlyAsync<InvalidOperationException>(async () => await Method());
128
```
129
130
### Collection Assertions (Assert class)
131
132
```csharp
133
Assert.Contains(expectedItem, collection);
134
Assert.DoesNotContain(unexpectedItem, collection);
135
Assert.ContainsSingle(collection); // exactly one element
136
Assert.HasCount(5, collection);
137
Assert.IsEmpty(collection);
138
Assert.IsNotEmpty(collection);
139
```
140
141
### String Assertions (Assert class)
142
143
```csharp
144
Assert.Contains("expected", actualString);
145
Assert.StartsWith("prefix", actualString);
146
Assert.EndsWith("suffix", actualString);
147
Assert.DoesNotStartWith("prefix", actualString);
148
Assert.DoesNotEndWith("suffix", actualString);
149
Assert.MatchesRegex(@"\d{3}-\d{4}", phoneNumber);
150
Assert.DoesNotMatchRegex(@"\d+", textOnly);
151
```
152
153
### Comparison Assertions
154
155
```csharp
156
Assert.IsGreaterThan(lowerBound, actual);
157
Assert.IsGreaterThanOrEqualTo(lowerBound, actual);
158
Assert.IsLessThan(upperBound, actual);
159
Assert.IsLessThanOrEqualTo(upperBound, actual);
160
Assert.IsInRange(actual, low, high);
161
Assert.IsPositive(number);
162
Assert.IsNegative(number);
163
```
164
165
### Type Assertions
166
167
```csharp
168
// MSTest 3.x - uses out parameter
169
Assert.IsInstanceOfType<MyClass>(obj, out var typed);
170
typed.DoSomething();
171
172
// MSTest 4.x - returns typed result directly
173
var typed = Assert.IsInstanceOfType<MyClass>(obj);
174
typed.DoSomething();
175
176
Assert.IsNotInstanceOfType<WrongType>(obj);
177
```
178
179
### Assert.That (MSTest 4.0+)
180
181
```csharp
182
Assert.That(result.Count > 0); // Auto-captures expression in failure message
183
```
184
185
### StringAssert Class
186
187
> **Note:** Prefer `Assert` class equivalents when available (e.g., `Assert.Contains("expected", actual)` over `StringAssert.Contains(actual, "expected")`).
188
189
```csharp
190
StringAssert.Contains(actualString, "expected");
191
StringAssert.StartsWith(actualString, "prefix");
192
StringAssert.EndsWith(actualString, "suffix");
193
StringAssert.Matches(actualString, new Regex(@"\d{3}-\d{4}"));
194
StringAssert.DoesNotMatch(actualString, new Regex(@"\d+"));
195
```
196
197
### CollectionAssert Class
198
199
> **Note:** Prefer `Assert` class equivalents when available (e.g., `Assert.Contains`).
200
201
```csharp
202
// Containment
203
CollectionAssert.Contains(collection, expectedItem);
204
CollectionAssert.DoesNotContain(collection, unexpectedItem);
205
206
// Equality (same elements, same order)
207
CollectionAssert.AreEqual(expectedCollection, actualCollection);
208
CollectionAssert.AreNotEqual(unexpectedCollection, actualCollection);
209
210
// Equivalence (same elements, any order)
211
CollectionAssert.AreEquivalent(expectedCollection, actualCollection);
212
CollectionAssert.AreNotEquivalent(unexpectedCollection, actualCollection);
213
214
// Subset checks
215
CollectionAssert.IsSubsetOf(subset, superset);
216
CollectionAssert.IsNotSubsetOf(notSubset, collection);
217
218
// Element validation
219
CollectionAssert.AllItemsAreInstancesOfType(collection, typeof(MyClass));
220
CollectionAssert.AllItemsAreNotNull(collection);
221
CollectionAssert.AllItemsAreUnique(collection);
222
```
223
224
## Data-Driven Tests
225
226
### DataRow
227
228
```csharp
229
[TestMethod]
230
[DataRow(1, 2, 3)]
231
[DataRow(0, 0, 0, DisplayName = "Zeros")]
232
[DataRow(-1, 1, 0, IgnoreMessage = "Known issue #123")] // MSTest 3.8+
233
public void Add_ReturnsSum(int a, int b, int expected)
234
{
235
Assert.AreEqual(expected, Calculator.Add(a, b));
236
}
237
```
238
239
### DynamicData
240
241
The data source can return any of the following types:
242
243
- `IEnumerable<(T1, T2, ...)>` (ValueTuple) - **preferred**, provides type safety (MSTest 3.7+)
244
- `IEnumerable<Tuple<T1, T2, ...>>` - provides type safety
245
- `IEnumerable<TestDataRow>` - provides type safety plus control over test metadata (display name, categories)
246
- `IEnumerable<object[]>` - **least preferred**, no type safety
247
248
> **Note:** When creating new test data methods, prefer `ValueTuple` or `TestDataRow` over `IEnumerable<object[]>`. The `object[]` approach provides no compile-time type checking and can lead to runtime errors from type mismatches.
249
250
```csharp
251
[TestMethod]
252
[DynamicData(nameof(TestData))]
253
public void DynamicTest(int a, int b, int expected)
254
{
255
Assert.AreEqual(expected, Calculator.Add(a, b));
256
}
257
258
// ValueTuple - preferred (MSTest 3.7+)
259
public static IEnumerable<(int a, int b, int expected)> TestData =>
260
[
261
(1, 2, 3),
262
(0, 0, 0),
263
];
264
265
// TestDataRow - when you need custom display names or metadata
266
public static IEnumerable<TestDataRow<(int a, int b, int expected)>> TestDataWithMetadata =>
267
[
268
new((1, 2, 3)) { DisplayName = "Positive numbers" },
269
new((0, 0, 0)) { DisplayName = "Zeros" },
270
new((-1, 1, 0)) { DisplayName = "Mixed signs", IgnoreMessage = "Known issue #123" },
271
];
272
273
// IEnumerable<object[]> - avoid for new code (no type safety)
274
public static IEnumerable<object[]> LegacyTestData =>
275
[
276
[1, 2, 3],
277
[0, 0, 0],
278
];
279
```
280
281
## TestContext
282
283
The `TestContext` class provides test run information, cancellation support, and output methods.
284
See [TestContext documentation](https://learn.microsoft.com/dotnet/core/testing/unit-testing-mstest-writing-tests-testcontext) for complete reference.
285
286
### Accessing TestContext
287
288
```csharp
289
// Property (MSTest suppresses CS8618 - don't use nullable or = null!)
290
public TestContext TestContext { get; set; }
291
292
// Constructor injection (MSTest 3.6+) - preferred for immutability
293
[TestClass]
294
public sealed class MyTests
295
{
296
private readonly TestContext _testContext;
297
298
public MyTests(TestContext testContext)
299
{
300
_testContext = testContext;
301
}
302
}
303
304
// Static methods receive it as parameter
305
[ClassInitialize]
306
public static void ClassInit(TestContext context) { }
307
308
// Optional for cleanup methods (MSTest 3.6+)
309
[ClassCleanup]
310
public static void ClassCleanup(TestContext context) { }
311
312
[AssemblyCleanup]
313
public static void AssemblyCleanup(TestContext context) { }
314
```
315
316
### Cancellation Token
317
318
Always use `TestContext.CancellationToken` for cooperative cancellation with `[Timeout]`:
319
320
```csharp
321
[TestMethod]
322
[Timeout(5000)]
323
public async Task LongRunningTest()
324
{
325
await _httpClient.GetAsync(url, TestContext.CancellationToken);
326
}
327
```
328
329
### Test Run Properties
330
331
```csharp
332
TestContext.TestName // Current test method name
333
TestContext.TestDisplayName // Display name (3.7+)
334
TestContext.CurrentTestOutcome // Pass/Fail/InProgress
335
TestContext.TestData // Parameterized test data (3.7+, in TestInitialize/Cleanup)
336
TestContext.TestException // Exception if test failed (3.7+, in TestCleanup)
337
TestContext.DeploymentDirectory // Directory with deployment items
338
```
339
340
### Output and Result Files
341
342
```csharp
343
// Write to test output (useful for debugging)
344
TestContext.WriteLine("Processing item {0}", itemId);
345
346
// Attach files to test results (logs, screenshots)
347
TestContext.AddResultFile(screenshotPath);
348
349
// Store/retrieve data across test methods
350
TestContext.Properties["SharedKey"] = computedValue;
351
```
352
353
## Advanced Features
354
355
### Retry for Flaky Tests (MSTest 3.9+)
356
357
```csharp
358
[TestMethod]
359
[Retry(3)]
360
public void FlakyTest() { }
361
```
362
363
### Conditional Execution (MSTest 3.10+)
364
365
Skip or run tests based on OS or CI environment:
366
367
```csharp
368
// OS-specific tests
369
[TestMethod]
370
[OSCondition(OperatingSystems.Windows)]
371
public void WindowsOnlyTest() { }
372
373
[TestMethod]
374
[OSCondition(OperatingSystems.Linux | OperatingSystems.MacOS)]
375
public void UnixOnlyTest() { }
376
377
[TestMethod]
378
[OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)]
379
public void SkipOnWindowsTest() { }
380
381
// CI environment tests
382
[TestMethod]
383
[CICondition] // Runs only in CI (default: ConditionMode.Include)
384
public void CIOnlyTest() { }
385
386
[TestMethod]
387
[CICondition(ConditionMode.Exclude)] // Skips in CI, runs locally
388
public void LocalOnlyTest() { }
389
```
390
391
### Parallelization
392
393
```csharp
394
// Assembly level
395
[assembly: Parallelize(Workers = 4, Scope = ExecutionScope.MethodLevel)]
396
397
// Disable for specific class
398
[TestClass]
399
[DoNotParallelize]
400
public sealed class SequentialTests { }
401
```
402
403
### Work Item Traceability (MSTest 3.8+)
404
405
Link tests to work items for traceability in test reports:
406
407
```csharp
408
// Azure DevOps work items
409
[TestMethod]
410
[WorkItem(12345)] // Links to work item #12345
411
public void Feature_Scenario_ExpectedBehavior() { }
412
413
// Multiple work items
414
[TestMethod]
415
[WorkItem(12345)]
416
[WorkItem(67890)]
417
public void Feature_CoversMultipleRequirements() { }
418
419
// GitHub issues (MSTest 3.8+)
420
[TestMethod]
421
[GitHubWorkItem("https://github.com/owner/repo/issues/42")]
422
public void BugFix_Issue42_IsResolved() { }
423
```
424
425
Work item associations appear in test results and can be used for:
426
- Tracing test coverage to requirements
427
- Linking bug fixes to regression tests
428
- Generating traceability reports in CI/CD pipelines
429
430
## Common Mistakes to Avoid
431
432
```csharp
433
// ❌ Wrong argument order
434
Assert.AreEqual(actual, expected);
435
// ✅ Correct
436
Assert.AreEqual(expected, actual);
437
438
// ❌ Using ExpectedException (obsolete)
439
[ExpectedException(typeof(ArgumentException))]
440
// ✅ Use Assert.Throws
441
Assert.Throws<ArgumentException>(() => Method());
442
443
// ❌ Using LINQ Single() - unclear exception
444
var item = items.Single();
445
// ✅ Use ContainsSingle - better failure message
446
var item = Assert.ContainsSingle(items);
447
448
// ❌ Hard cast - unclear exception
449
var handler = (MyHandler)result;
450
// ✅ Type assertion - shows actual type on failure
451
var handler = Assert.IsInstanceOfType<MyHandler>(result);
452
453
// ❌ Ignoring cancellation token
454
await client.GetAsync(url, CancellationToken.None);
455
// ✅ Flow test cancellation
456
await client.GetAsync(url, TestContext.CancellationToken);
457
458
// ❌ Making TestContext nullable - leads to unnecessary null checks
459
public TestContext? TestContext { get; set; }
460
// ❌ Using null! - MSTest already suppresses CS8618 for this property
461
public TestContext TestContext { get; set; } = null!;
462
// ✅ Declare without nullable or initializer - MSTest handles the warning
463
public TestContext TestContext { get; set; }
464
```
465
466
## Test Organization
467
468
- Group tests by feature or component
469
- Use `[TestCategory("Category")]` for filtering
470
- Use `[TestProperty("Name", "Value")]` for custom metadata (e.g., `[TestProperty("Bug", "12345")]`)
471
- Use `[Priority(1)]` for critical tests
472
- Enable relevant MSTest analyzers (MSTEST0020 for constructor preference)
473
474
## Mocking and Isolation
475
476
- Use Moq or NSubstitute for mocking dependencies
477
- Use interfaces to facilitate mocking
478
- Mock dependencies to isolate units under test
479