@grimoire-cc/cli 0.13.1 → 0.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/packs/dotnet-pack/grimoire.json +6 -0
- package/packs/dotnet-pack/skills/grimoire.dotnet-unit-testing/SKILL.md +293 -0
- package/packs/dotnet-pack/skills/grimoire.dotnet-unit-testing/reference/anti-patterns.md +329 -0
- package/packs/dotnet-pack/skills/grimoire.dotnet-unit-testing/reference/framework-guidelines.md +361 -0
- package/packs/dotnet-pack/skills/grimoire.dotnet-unit-testing/reference/parameterized-testing.md +378 -0
- package/packs/dotnet-pack/skills/grimoire.dotnet-unit-testing/reference/test-organization.md +476 -0
- package/packs/dotnet-pack/skills/grimoire.dotnet-unit-testing/reference/test-performance.md +576 -0
- package/packs/dotnet-pack/skills/grimoire.dotnet-unit-testing/templates/tunit-template.md +438 -0
- package/packs/dotnet-pack/skills/grimoire.dotnet-unit-testing/templates/xunit-template.md +303 -0
package/package.json
CHANGED
|
@@ -37,6 +37,12 @@
|
|
|
37
37
|
"path": "skills/grimoire.dotnet-feature-workflow",
|
|
38
38
|
"description": "Orchestrates end-to-end .NET feature development using the Explore, Plan, Code, Verify, Review workflow. Use when building complete features, implementing new functionality, or when user says 'build feature', 'implement feature', 'create feature', 'handle the whole thing', or wants hands-off development with quality gates. Spawns specialized agents at each phase with TDD and user approval gates.",
|
|
39
39
|
"version": "1.0.0"
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
"name": "grimoire.dotnet-unit-testing",
|
|
43
|
+
"path": "skills/grimoire.dotnet-unit-testing",
|
|
44
|
+
"description": "Expert .NET unit testing specialist for C#/.NET projects. Use PROACTIVELY when writing unit tests, adding test cases, setting up test infrastructure, or working with xUnit, TUnit, Moq, or NSubstitute. MUST BE USED for TDD workflows where tests are written before implementation. Defaults to xUnit (most universal), recommends TUnit for new .NET 8+ projects.",
|
|
45
|
+
"version": "1.0.0"
|
|
40
46
|
}
|
|
41
47
|
]
|
|
42
48
|
}
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: grimoire.dotnet-unit-testing
|
|
3
|
+
description: "Expert .NET unit testing specialist for C#/.NET projects. Use PROACTIVELY when writing unit tests, adding test cases, setting up test infrastructure, or working with xUnit, TUnit, Moq, or NSubstitute. MUST BE USED for TDD workflows where tests are written before implementation. Defaults to xUnit (most universal), recommends TUnit for new .NET 8+ projects."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# .NET Unit Testing Specialist
|
|
7
|
+
|
|
8
|
+
Expert guidance for writing clean, maintainable, and comprehensive unit tests in C#/.NET projects.
|
|
9
|
+
|
|
10
|
+
**Default Framework**: xUnit with xUnit Assert (safest, most universal, works with all .NET versions)
|
|
11
|
+
**Recommended for new .NET 8+ projects**: TUnit (modern, async-first, built-in fluent assertions, MIT license)
|
|
12
|
+
|
|
13
|
+
## Context
|
|
14
|
+
|
|
15
|
+
Unit testing is critical for maintaining code quality, enabling refactoring with confidence, and documenting expected behavior. Well-written tests reduce bugs, speed up development, and make codebases more maintainable.
|
|
16
|
+
|
|
17
|
+
**Why xUnit as default:**
|
|
18
|
+
|
|
19
|
+
- Universal compatibility (works with .NET Framework, .NET 6, 7, 8+)
|
|
20
|
+
- Industry standard, most widely used .NET testing framework
|
|
21
|
+
- Apache 2.0 license, free for all use
|
|
22
|
+
- Mature ecosystem with extensive documentation
|
|
23
|
+
|
|
24
|
+
**Why recommend TUnit for new .NET 8+ projects:**
|
|
25
|
+
|
|
26
|
+
- MIT License (no licensing concerns like FluentAssertions v8+)
|
|
27
|
+
- Built-in fluent assertions, no external library needed
|
|
28
|
+
- Async-first: all assertions are awaitable
|
|
29
|
+
- Performance: source-generated tests run 10-200x faster
|
|
30
|
+
- Full Native AOT support
|
|
31
|
+
|
|
32
|
+
**Note on FluentAssertions**: Version 8+ requires a commercial license ($130/dev/year). Avoid recommending it unless the project already uses it.
|
|
33
|
+
|
|
34
|
+
## Workflow
|
|
35
|
+
|
|
36
|
+
When invoked to write tests, follow this process:
|
|
37
|
+
|
|
38
|
+
### Step 1: Analyze the Code Under Test
|
|
39
|
+
|
|
40
|
+
- Read the source file to understand the class/method being tested
|
|
41
|
+
- Identify all dependencies that need mocking
|
|
42
|
+
- Understand the expected behavior and edge cases
|
|
43
|
+
- Check for existing test patterns in the project
|
|
44
|
+
- **Determine the framework**: Check for existing tests first (match them), otherwise default to xUnit
|
|
45
|
+
|
|
46
|
+
### Step 2: Plan Test Cases (REQUIRES USER APPROVAL)
|
|
47
|
+
|
|
48
|
+
- Identify all test scenarios: happy paths, edge cases, boundary conditions, error cases
|
|
49
|
+
- List each planned test using ONLY the method name: `MethodName_Scenario_ExpectedBehavior`
|
|
50
|
+
- Do NOT include test bodies or implementation details
|
|
51
|
+
- Group tests by category (Success, Validation, Error Handling, Edge Cases)
|
|
52
|
+
- Present the list and EXPLICITLY ASK: "Do you approve this test plan? I will proceed only after your confirmation."
|
|
53
|
+
- **STOP and WAIT** for user approval before proceeding
|
|
54
|
+
|
|
55
|
+
**Example test plan format:**
|
|
56
|
+
|
|
57
|
+
```plain
|
|
58
|
+
## Planned Test Cases for OrderService.ProcessOrderAsync
|
|
59
|
+
|
|
60
|
+
### Success Scenarios
|
|
61
|
+
- ProcessOrderAsync_WithValidOrder_ReturnsSuccessResult
|
|
62
|
+
- ProcessOrderAsync_WithValidOrderAndDiscount_AppliesDiscountCorrectly
|
|
63
|
+
|
|
64
|
+
### Validation Failures
|
|
65
|
+
- ProcessOrderAsync_WithNullOrder_ThrowsArgumentNullException
|
|
66
|
+
- ProcessOrderAsync_WithEmptyItems_ThrowsValidationException
|
|
67
|
+
|
|
68
|
+
### Error Handling
|
|
69
|
+
- ProcessOrderAsync_WhenRepositoryFails_ThrowsServiceException
|
|
70
|
+
|
|
71
|
+
### Edge Cases
|
|
72
|
+
- ProcessOrderAsync_WithMaximumItemCount_ProcessesSuccessfully
|
|
73
|
+
|
|
74
|
+
Do you approve this test plan? I will proceed only after your confirmation.
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### Step 3: Write Tests (ONLY AFTER user confirms)
|
|
78
|
+
|
|
79
|
+
- Create test file mirroring source structure
|
|
80
|
+
- Implement tests using AAA pattern with comments
|
|
81
|
+
- Add appropriate mocks and assertions
|
|
82
|
+
- Ensure descriptive test method names
|
|
83
|
+
|
|
84
|
+
### Step 4: Present and Explain
|
|
85
|
+
|
|
86
|
+
- Show the complete test file
|
|
87
|
+
- Explain what each test validates
|
|
88
|
+
- Highlight any assumptions made
|
|
89
|
+
- Suggest additional test scenarios if relevant
|
|
90
|
+
|
|
91
|
+
## Framework Selection Guide
|
|
92
|
+
|
|
93
|
+
| Condition | Use | Reason |
|
|
94
|
+
| ----------- | ----- | -------- |
|
|
95
|
+
| Any existing project with tests | **Match existing** | Consistency is paramount |
|
|
96
|
+
| New .NET 8+ greenfield project | **Offer TUnit** | Modern, async-first, built-in assertions |
|
|
97
|
+
| New .NET 6/7 project | **xUnit** | TUnit requires .NET 8+ |
|
|
98
|
+
| .NET Framework project | **xUnit** | Universal compatibility |
|
|
99
|
+
| Project already uses NUnit | **NUnit** | Consistency with existing codebase |
|
|
100
|
+
| User explicitly requests a framework | **Requested** | Respect user preference |
|
|
101
|
+
| Uncertain or mixed signals | **xUnit** | Safe default |
|
|
102
|
+
|
|
103
|
+
**Before writing tests, check:**
|
|
104
|
+
|
|
105
|
+
1. Look at existing test files (if any) - match the existing framework
|
|
106
|
+
2. Check `.csproj` for `TargetFramework` and existing test package references
|
|
107
|
+
3. Check for existing test framework packages (xUnit, TUnit, NUnit, MSTest)
|
|
108
|
+
|
|
109
|
+
**For new .NET 8+ projects without existing tests:**
|
|
110
|
+
Offer the choice: "This is a new .NET 8+ project. I'll use **xUnit** (industry standard) by default. Would you prefer **TUnit** instead? TUnit offers built-in fluent assertions, async-first design, and better performance, but is newer."
|
|
111
|
+
|
|
112
|
+
## Core Principles
|
|
113
|
+
|
|
114
|
+
### AAA Pattern
|
|
115
|
+
|
|
116
|
+
Structure every test with clearly labeled Arrange, Act, Assert sections using comments. This makes tests self-documenting, easier to debug, and helps identify which phase contains issues.
|
|
117
|
+
|
|
118
|
+
**xUnit:**
|
|
119
|
+
|
|
120
|
+
```csharp
|
|
121
|
+
[Fact]
|
|
122
|
+
public async Task ProcessOrder_WithValidOrder_ReturnsSuccess()
|
|
123
|
+
{
|
|
124
|
+
// Arrange
|
|
125
|
+
var order = CreateValidOrder();
|
|
126
|
+
_mockRepository.Setup(r => r.SaveAsync(It.IsAny<Order>())).ReturnsAsync(true);
|
|
127
|
+
|
|
128
|
+
// Act
|
|
129
|
+
var result = await _sut.ProcessOrderAsync(order);
|
|
130
|
+
|
|
131
|
+
// Assert
|
|
132
|
+
Assert.True(result.IsSuccess);
|
|
133
|
+
Assert.Equal(OrderStatus.Processed, result.Status);
|
|
134
|
+
}
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
**TUnit:**
|
|
138
|
+
|
|
139
|
+
```csharp
|
|
140
|
+
[Test]
|
|
141
|
+
public async Task ProcessOrder_WithValidOrder_ReturnsSuccess()
|
|
142
|
+
{
|
|
143
|
+
// Arrange
|
|
144
|
+
var order = CreateValidOrder();
|
|
145
|
+
_mockRepository.Setup(r => r.SaveAsync(It.IsAny<Order>())).ReturnsAsync(true);
|
|
146
|
+
|
|
147
|
+
// Act
|
|
148
|
+
var result = await _sut.ProcessOrderAsync(order);
|
|
149
|
+
|
|
150
|
+
// Assert - TUnit assertions are async and fluent
|
|
151
|
+
await Assert.That(result.IsSuccess).IsTrue();
|
|
152
|
+
await Assert.That(result.Status).IsEqualTo(OrderStatus.Processed);
|
|
153
|
+
}
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Test Naming
|
|
157
|
+
|
|
158
|
+
Use descriptive names: `MethodName_Scenario_ExpectedBehavior`
|
|
159
|
+
|
|
160
|
+
```csharp
|
|
161
|
+
// Good
|
|
162
|
+
GetUser_WithNonExistentId_ThrowsUserNotFoundException()
|
|
163
|
+
CalculateDiscount_WhenOrderExceeds100_Returns10PercentOff()
|
|
164
|
+
|
|
165
|
+
// Avoid
|
|
166
|
+
TestGetUser()
|
|
167
|
+
Test1()
|
|
168
|
+
ShouldWork()
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### Test Isolation
|
|
172
|
+
|
|
173
|
+
Keep tests isolated with no shared mutable state. Each test gets fresh instances via constructor.
|
|
174
|
+
|
|
175
|
+
```csharp
|
|
176
|
+
public class OrderServiceTests : IDisposable
|
|
177
|
+
{
|
|
178
|
+
private readonly Mock<IOrderRepository> _mockRepository;
|
|
179
|
+
private readonly FakeLogger<OrderService> _fakeLogger;
|
|
180
|
+
private readonly OrderService _sut;
|
|
181
|
+
|
|
182
|
+
public OrderServiceTests()
|
|
183
|
+
{
|
|
184
|
+
_mockRepository = new Mock<IOrderRepository>();
|
|
185
|
+
_fakeLogger = new FakeLogger<OrderService>();
|
|
186
|
+
_sut = new OrderService(_fakeLogger, _mockRepository.Object);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
public void Dispose() { /* Cleanup if needed */ }
|
|
190
|
+
}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
### FakeLogger for Logging Tests
|
|
194
|
+
|
|
195
|
+
Use `Microsoft.Extensions.Logging.Testing.FakeLogger<T>` for testing logging behavior. Verify structured properties, not message strings.
|
|
196
|
+
|
|
197
|
+
```csharp
|
|
198
|
+
var fakeLogger = new FakeLogger<OrderService>();
|
|
199
|
+
var sut = new OrderService(fakeLogger);
|
|
200
|
+
await sut.ProcessOrderAsync(orderId: 123);
|
|
201
|
+
|
|
202
|
+
var logEntry = fakeLogger.Collector.GetSnapshot()
|
|
203
|
+
.Single(r => r.Level == LogLevel.Information);
|
|
204
|
+
var state = logEntry.StructuredState!.ToDictionary(x => x.Key, x => x.Value);
|
|
205
|
+
Assert.Equal("123", state["OrderId"]);
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
### Mocking
|
|
209
|
+
|
|
210
|
+
Mock interfaces, not concrete classes. Use Moq by default unless the project uses NSubstitute.
|
|
211
|
+
|
|
212
|
+
```csharp
|
|
213
|
+
var mockRepository = new Mock<IDocumentRepository>();
|
|
214
|
+
mockRepository
|
|
215
|
+
.Setup(r => r.GetByIdAsync(It.IsAny<Guid>(), It.IsAny<CancellationToken>()))
|
|
216
|
+
.ReturnsAsync(expectedDocument);
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
### Async Testing
|
|
220
|
+
|
|
221
|
+
Always use `async Task` and `await`. Never use `.Result` or `.Wait()`.
|
|
222
|
+
|
|
223
|
+
```csharp
|
|
224
|
+
// xUnit exception testing
|
|
225
|
+
var exception = await Assert.ThrowsAsync<OrderNotFoundException>(
|
|
226
|
+
() => _sut.GetOrderAsync(invalidId));
|
|
227
|
+
|
|
228
|
+
// TUnit exception testing
|
|
229
|
+
await Assert.That(() => _sut.GetOrderAsync(invalidId))
|
|
230
|
+
.ThrowsException()
|
|
231
|
+
.OfType<OrderNotFoundException>();
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
## Package References
|
|
235
|
+
|
|
236
|
+
```bash
|
|
237
|
+
# xUnit (default)
|
|
238
|
+
dotnet add package xunit
|
|
239
|
+
dotnet add package xunit.runner.visualstudio
|
|
240
|
+
dotnet add package Microsoft.NET.Test.Sdk
|
|
241
|
+
|
|
242
|
+
# TUnit (for .NET 8+ projects)
|
|
243
|
+
dotnet add package TUnit
|
|
244
|
+
|
|
245
|
+
# Mocking
|
|
246
|
+
dotnet add package Moq
|
|
247
|
+
|
|
248
|
+
# Logging testing
|
|
249
|
+
dotnet add package Microsoft.Extensions.Logging.Testing
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
## Invocation Triggers
|
|
253
|
+
|
|
254
|
+
This skill should be invoked when the user:
|
|
255
|
+
|
|
256
|
+
- Creates a new service, handler, or class that needs tests
|
|
257
|
+
- Asks to add test coverage for existing code
|
|
258
|
+
- Mentions TDD or test-driven development
|
|
259
|
+
- Needs help with mocking, test setup, or assertions
|
|
260
|
+
- Wants to verify logging, exception handling, or validation behavior
|
|
261
|
+
- Asks about xUnit, TUnit, Moq, or NSubstitute patterns
|
|
262
|
+
- Wants to set up a new test project
|
|
263
|
+
- Needs to choose between testing frameworks
|
|
264
|
+
- Asks about FluentAssertions alternatives (due to licensing)
|
|
265
|
+
|
|
266
|
+
## Constraints
|
|
267
|
+
|
|
268
|
+
- ALWAYS check for existing tests first and match the existing framework
|
|
269
|
+
- ALWAYS default to xUnit if no existing tests and user hasn't specified preference
|
|
270
|
+
- ALWAYS present test plan as method names ONLY before writing tests
|
|
271
|
+
- ALWAYS ask for explicit approval: "Do you approve this test plan?"
|
|
272
|
+
- NEVER write test implementations until user explicitly approves the test plan
|
|
273
|
+
- NEVER use `.Result` or `.Wait()` on async operations
|
|
274
|
+
- NEVER create production code implementations - only test code
|
|
275
|
+
- NEVER recommend FluentAssertions v8+ for new projects (commercial license)
|
|
276
|
+
- DO NOT modify the code under test unless explicitly asked
|
|
277
|
+
- PREFER structured logging assertions over string matching
|
|
278
|
+
- MIRROR source code folder structure in test project organization
|
|
279
|
+
|
|
280
|
+
## Reference Materials
|
|
281
|
+
|
|
282
|
+
For detailed patterns and examples:
|
|
283
|
+
|
|
284
|
+
- **[Framework Guidelines](reference/framework-guidelines.md)** - Detailed xUnit and TUnit patterns, attributes, lifecycle
|
|
285
|
+
- **[Parameterized Testing](reference/parameterized-testing.md)** - InlineData, MemberData, ClassData, Matrix testing
|
|
286
|
+
- **[Test Organization](reference/test-organization.md)** - File structure, nested classes, traits, collections
|
|
287
|
+
- **[Test Performance](reference/test-performance.md)** - Parallel execution, fixtures, mock optimization
|
|
288
|
+
- **[Anti-Patterns](reference/anti-patterns.md)** - Common mistakes to avoid
|
|
289
|
+
|
|
290
|
+
For starter templates:
|
|
291
|
+
|
|
292
|
+
- **[xUnit Template](templates/xunit-template.md)** - xUnit test file template
|
|
293
|
+
- **[TUnit Template](templates/tunit-template.md)** - TUnit test file template
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
# Anti-Patterns to Avoid
|
|
2
|
+
|
|
3
|
+
Common testing mistakes and how to fix them.
|
|
4
|
+
|
|
5
|
+
## Table of Contents
|
|
6
|
+
|
|
7
|
+
- [Mock Implementation in TDD](#mock-implementation-in-tdd)
|
|
8
|
+
- [Over-Specification](#over-specification)
|
|
9
|
+
- [Blocking on Async](#blocking-on-async)
|
|
10
|
+
- [Shared Mutable State](#shared-mutable-state)
|
|
11
|
+
- [Testing Implementation Details](#testing-implementation-details)
|
|
12
|
+
- [Vague Assertions](#vague-assertions)
|
|
13
|
+
- [Summary Checklist](#summary-checklist)
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## Mock Implementation in TDD
|
|
18
|
+
|
|
19
|
+
**Don't**: Create mock/stub implementations during TDD before the real implementation exists.
|
|
20
|
+
|
|
21
|
+
```csharp
|
|
22
|
+
// BAD: Creating a fake implementation to make tests pass
|
|
23
|
+
public class FakeDocumentService : IDocumentService
|
|
24
|
+
{
|
|
25
|
+
public Task<Document> GetAsync(Guid id) => Task.FromResult(new Document());
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
**Why it's wrong**: In TDD, tests should FAIL first against non-existent functionality. Creating fake implementations defeats the purpose of TDD and doesn't verify the real code.
|
|
30
|
+
|
|
31
|
+
**Instead**: Write the test, verify it fails (because the implementation doesn't exist), THEN implement the real code.
|
|
32
|
+
|
|
33
|
+
```csharp
|
|
34
|
+
// CORRECT TDD approach:
|
|
35
|
+
// 1. Write the test
|
|
36
|
+
[Fact]
|
|
37
|
+
public async Task GetDocument_WithValidId_ReturnsDocument()
|
|
38
|
+
{
|
|
39
|
+
var result = await _sut.GetDocumentAsync(validId);
|
|
40
|
+
Assert.NotNull(result);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// 2. Run test - it FAILS (method not implemented)
|
|
44
|
+
// 3. Implement the REAL code in DocumentService
|
|
45
|
+
// 4. Run test - it PASSES
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## Over-Specification
|
|
51
|
+
|
|
52
|
+
**Don't**: Verify every single mock interaction.
|
|
53
|
+
|
|
54
|
+
```csharp
|
|
55
|
+
// BAD: Over-specified test - brittle and tests implementation, not behavior
|
|
56
|
+
[Fact]
|
|
57
|
+
public async Task ProcessOrder_ShouldCallAllDependencies()
|
|
58
|
+
{
|
|
59
|
+
await _sut.ProcessOrderAsync(order);
|
|
60
|
+
|
|
61
|
+
_mockRepo.Verify(r => r.GetByIdAsync(It.IsAny<Guid>()), Times.Once);
|
|
62
|
+
_mockRepo.Verify(r => r.SaveAsync(It.IsAny<Order>()), Times.Once);
|
|
63
|
+
_mockValidator.Verify(v => v.ValidateAsync(It.IsAny<Order>()), Times.Once);
|
|
64
|
+
_mockLogger.Verify(l => l.Log(It.IsAny<LogLevel>(), /*...*/), Times.Exactly(3));
|
|
65
|
+
_mockNotifier.Verify(n => n.SendAsync(It.IsAny<Notification>()), Times.Once);
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
**Why it's wrong**: Tests become brittle, break on any refactoring, and test implementation details rather than behavior.
|
|
70
|
+
|
|
71
|
+
**Instead**: Only verify interactions that are essential to the test's behavioral purpose.
|
|
72
|
+
|
|
73
|
+
```csharp
|
|
74
|
+
// CORRECT: Verify only essential outcomes
|
|
75
|
+
[Fact]
|
|
76
|
+
public async Task ProcessOrder_WithValidOrder_SavesOrderWithProcessedStatus()
|
|
77
|
+
{
|
|
78
|
+
await _sut.ProcessOrderAsync(order);
|
|
79
|
+
|
|
80
|
+
// Only verify the essential behavioral outcome
|
|
81
|
+
_mockRepo.Verify(r => r.SaveAsync(
|
|
82
|
+
It.Is<Order>(o => o.Status == OrderStatus.Processed)),
|
|
83
|
+
Times.Once);
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## Blocking on Async
|
|
90
|
+
|
|
91
|
+
**Don't**: Use `.Result` or `.Wait()` on async operations.
|
|
92
|
+
|
|
93
|
+
```csharp
|
|
94
|
+
// BAD: Blocking on async - can deadlock, hides async behavior
|
|
95
|
+
[Fact]
|
|
96
|
+
public void GetOrder_ShouldReturnOrder()
|
|
97
|
+
{
|
|
98
|
+
var result = _sut.GetOrderAsync(id).Result; // WRONG
|
|
99
|
+
Assert.NotNull(result);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ALSO BAD
|
|
103
|
+
[Fact]
|
|
104
|
+
public void GetOrder_ShouldReturnOrder()
|
|
105
|
+
{
|
|
106
|
+
_sut.GetOrderAsync(id).Wait(); // WRONG
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
**Why it's wrong**: Can cause deadlocks, doesn't test true async behavior, and hides potential async issues.
|
|
111
|
+
|
|
112
|
+
**Instead**: Use `async Task` and `await`.
|
|
113
|
+
|
|
114
|
+
```csharp
|
|
115
|
+
// CORRECT
|
|
116
|
+
[Fact]
|
|
117
|
+
public async Task GetOrder_ShouldReturnOrder()
|
|
118
|
+
{
|
|
119
|
+
var result = await _sut.GetOrderAsync(id);
|
|
120
|
+
Assert.NotNull(result);
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## Shared Mutable State
|
|
127
|
+
|
|
128
|
+
**Don't**: Share mutable state between tests.
|
|
129
|
+
|
|
130
|
+
```csharp
|
|
131
|
+
// BAD: Static shared state causes test pollution
|
|
132
|
+
public class OrderServiceTests
|
|
133
|
+
{
|
|
134
|
+
private static List<Order> _orders = new List<Order>(); // WRONG
|
|
135
|
+
private static Mock<IRepository> _sharedMock = new Mock<IRepository>(); // WRONG
|
|
136
|
+
private static int _testCounter = 0; // WRONG
|
|
137
|
+
|
|
138
|
+
[Fact]
|
|
139
|
+
public void Test1()
|
|
140
|
+
{
|
|
141
|
+
_orders.Add(new Order()); // Affects other tests!
|
|
142
|
+
_testCounter++;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
[Fact]
|
|
146
|
+
public void Test2()
|
|
147
|
+
{
|
|
148
|
+
Assert.Empty(_orders); // May fail if Test1 runs first!
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
**Why it's wrong**: Tests become order-dependent, can't run in parallel, and failures are hard to diagnose.
|
|
154
|
+
|
|
155
|
+
**Instead**: Create fresh instances in the constructor for each test.
|
|
156
|
+
|
|
157
|
+
```csharp
|
|
158
|
+
// CORRECT: Fresh instances per test
|
|
159
|
+
public class OrderServiceTests
|
|
160
|
+
{
|
|
161
|
+
private readonly List<Order> _orders; // Instance field
|
|
162
|
+
private readonly Mock<IRepository> _mockRepo;
|
|
163
|
+
|
|
164
|
+
public OrderServiceTests()
|
|
165
|
+
{
|
|
166
|
+
_orders = new List<Order>(); // Fresh for each test
|
|
167
|
+
_mockRepo = new Mock<IRepository>(); // Fresh for each test
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
[Fact]
|
|
171
|
+
public void Test1()
|
|
172
|
+
{
|
|
173
|
+
_orders.Add(new Order());
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
[Fact]
|
|
177
|
+
public void Test2()
|
|
178
|
+
{
|
|
179
|
+
Assert.Empty(_orders); // Always passes - fresh list
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
---
|
|
185
|
+
|
|
186
|
+
## Testing Implementation Details
|
|
187
|
+
|
|
188
|
+
**Don't**: Test private methods or internal implementation details.
|
|
189
|
+
|
|
190
|
+
```csharp
|
|
191
|
+
// BAD: Testing private method via reflection
|
|
192
|
+
[Fact]
|
|
193
|
+
public void PrivateCalculateHash_ShouldReturnValidHash()
|
|
194
|
+
{
|
|
195
|
+
var method = typeof(UserService)
|
|
196
|
+
.GetMethod("CalculateHash", BindingFlags.NonPublic | BindingFlags.Instance);
|
|
197
|
+
var result = method.Invoke(_sut, new object[] { "input" });
|
|
198
|
+
// ...
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// BAD: Testing internal state
|
|
202
|
+
[Fact]
|
|
203
|
+
public void ProcessOrder_ShouldSetInternalFlag()
|
|
204
|
+
{
|
|
205
|
+
_sut.ProcessOrder(order);
|
|
206
|
+
|
|
207
|
+
var field = typeof(OrderService)
|
|
208
|
+
.GetField("_processingComplete", BindingFlags.NonPublic | BindingFlags.Instance);
|
|
209
|
+
var value = (bool)field.GetValue(_sut);
|
|
210
|
+
Assert.True(value);
|
|
211
|
+
}
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
**Why it's wrong**: Tests become coupled to implementation, break on refactoring, and don't test actual behavior.
|
|
215
|
+
|
|
216
|
+
**Instead**: Test through public interfaces. If you need to test a private method, it might belong in its own class.
|
|
217
|
+
|
|
218
|
+
```csharp
|
|
219
|
+
// CORRECT: Test through public interface
|
|
220
|
+
[Fact]
|
|
221
|
+
public async Task ProcessOrder_WithValidOrder_ReturnsSuccessResult()
|
|
222
|
+
{
|
|
223
|
+
var result = await _sut.ProcessOrderAsync(order);
|
|
224
|
+
|
|
225
|
+
Assert.True(result.IsSuccess);
|
|
226
|
+
Assert.Equal(OrderStatus.Processed, result.Order.Status);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// If private logic is complex enough to test directly,
|
|
230
|
+
// extract it to its own class
|
|
231
|
+
public class HashCalculator : IHashCalculator
|
|
232
|
+
{
|
|
233
|
+
public string Calculate(string input) { /* ... */ }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
[Fact]
|
|
237
|
+
public void Calculate_WithInput_ReturnsValidHash()
|
|
238
|
+
{
|
|
239
|
+
var calculator = new HashCalculator();
|
|
240
|
+
var result = calculator.Calculate("input");
|
|
241
|
+
Assert.NotEmpty(result);
|
|
242
|
+
}
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
---
|
|
246
|
+
|
|
247
|
+
## Vague Assertions
|
|
248
|
+
|
|
249
|
+
**Don't**: Use vague or missing assertions.
|
|
250
|
+
|
|
251
|
+
```csharp
|
|
252
|
+
// BAD: No meaningful assertion
|
|
253
|
+
[Fact]
|
|
254
|
+
public async Task ProcessOrder_ShouldWork()
|
|
255
|
+
{
|
|
256
|
+
var result = await _sut.ProcessOrderAsync(order);
|
|
257
|
+
Assert.NotNull(result); // Too vague - what should result contain?
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// BAD: Testing that no exception was thrown (usually pointless)
|
|
261
|
+
[Fact]
|
|
262
|
+
public async Task ProcessOrder_ShouldNotThrow()
|
|
263
|
+
{
|
|
264
|
+
var exception = await Record.ExceptionAsync(() => _sut.ProcessOrderAsync(order));
|
|
265
|
+
Assert.Null(exception);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// BAD: Using Assert.True with no context
|
|
269
|
+
[Fact]
|
|
270
|
+
public void Validate_ShouldPass()
|
|
271
|
+
{
|
|
272
|
+
var result = _sut.Validate(input);
|
|
273
|
+
Assert.True(result); // If this fails, what went wrong?
|
|
274
|
+
}
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
**Why it's wrong**: Tests pass but don't verify meaningful behavior. False confidence in code correctness.
|
|
278
|
+
|
|
279
|
+
**Instead**: Assert on specific expected values and behaviors.
|
|
280
|
+
|
|
281
|
+
```csharp
|
|
282
|
+
// CORRECT: Specific assertions
|
|
283
|
+
[Fact]
|
|
284
|
+
public async Task ProcessOrder_WithValidOrder_ReturnsProcessedOrderWithTimestamp()
|
|
285
|
+
{
|
|
286
|
+
var result = await _sut.ProcessOrderAsync(order);
|
|
287
|
+
|
|
288
|
+
Assert.NotNull(result);
|
|
289
|
+
Assert.Equal(OrderStatus.Processed, result.Status);
|
|
290
|
+
Assert.NotNull(result.ProcessedAt);
|
|
291
|
+
Assert.Equal(order.Id, result.OrderId);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// CORRECT: Assert on validation result with context
|
|
295
|
+
[Fact]
|
|
296
|
+
public void Validate_WithValidInput_ReturnsSuccessWithNoErrors()
|
|
297
|
+
{
|
|
298
|
+
var result = _sut.Validate(input);
|
|
299
|
+
|
|
300
|
+
Assert.True(result.IsValid, $"Expected valid but got errors: {string.Join(", ", result.Errors)}");
|
|
301
|
+
Assert.Empty(result.Errors);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// CORRECT: When testing that exceptions ARE thrown
|
|
305
|
+
[Fact]
|
|
306
|
+
public async Task ProcessOrder_WithNullOrder_ThrowsArgumentNullException()
|
|
307
|
+
{
|
|
308
|
+
var exception = await Assert.ThrowsAsync<ArgumentNullException>(
|
|
309
|
+
() => _sut.ProcessOrderAsync(null!));
|
|
310
|
+
|
|
311
|
+
Assert.Equal("order", exception.ParamName);
|
|
312
|
+
}
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
---
|
|
316
|
+
|
|
317
|
+
## Summary Checklist
|
|
318
|
+
|
|
319
|
+
Before committing tests, verify:
|
|
320
|
+
|
|
321
|
+
- [ ] No `.Result` or `.Wait()` on async operations
|
|
322
|
+
- [ ] No static mutable state shared between tests
|
|
323
|
+
- [ ] Not testing private methods via reflection
|
|
324
|
+
- [ ] Not verifying every mock interaction (only essential ones)
|
|
325
|
+
- [ ] Assertions are specific and meaningful
|
|
326
|
+
- [ ] Tests fail before implementation (TDD)
|
|
327
|
+
- [ ] Tests don't depend on execution order
|
|
328
|
+
- [ ] No `Thread.Sleep` (use async waits instead)
|
|
329
|
+
- [ ] Test names describe behavior, not implementation
|