|
41 | 41 | - Even in mock/test handlers, follow proper disposal patterns |
42 | 42 | - Consider using `using` statements or ensure test handlers dispose responses |
43 | 43 | - This applies to all `IDisposable` test objects to avoid analyzer warnings |
| 44 | +- **Disable parallel execution for tests with shared state**: |
| 45 | + - Tests that modify environment variables must disable parallelization |
| 46 | + - Tests that access shared file system resources must run sequentially |
| 47 | + - Use `[CollectionDefinition("TestName", DisableParallelization = true)]` pattern |
| 48 | + - Add `[Collection("TestName")]` attribute to test class |
| 49 | + - **Pattern to follow**: |
| 50 | + ```csharp |
| 51 | + /// <summary> |
| 52 | + /// Tests must run sequentially because they modify environment variables. |
| 53 | + /// </summary> |
| 54 | + [CollectionDefinition("EnvTests", DisableParallelization = true)] |
| 55 | + public class EnvTestCollection { } |
| 56 | + |
| 57 | + [Collection("EnvTests")] |
| 58 | + public class MyTests |
| 59 | + { |
| 60 | + [Fact] |
| 61 | + public void Test_ModifiesEnvironmentVariable() |
| 62 | + { |
| 63 | + Environment.SetEnvironmentVariable("VAR", "value"); |
| 64 | + try |
| 65 | + { |
| 66 | + // Test logic |
| 67 | + } |
| 68 | + finally |
| 69 | + { |
| 70 | + Environment.SetEnvironmentVariable("VAR", null); |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + ``` |
| 75 | + |
| 76 | +### Resource Management |
| 77 | +- **Always dispose IDisposable objects** to prevent resource leaks: |
| 78 | + - `HttpResponseMessage` returned by `HttpClient.GetAsync()`, `PostAsync()`, etc. must be disposed |
| 79 | + - Use `using` statements for automatic disposal: `using var response = await httpClient.GetAsync(...);` |
| 80 | + - Even when checking `IsSuccessStatusCode` or reading content, wrap in `using` |
| 81 | + - This applies to all HTTP responses, streams, file handles, and other disposable resources |
| 82 | + - **Pattern to follow**: |
| 83 | + ```csharp |
| 84 | + // CORRECT - Dispose HttpResponseMessage |
| 85 | + using var response = await httpClient.GetAsync(url, cancellationToken); |
| 86 | + if (!response.IsSuccessStatusCode) { return null; } |
| 87 | + var content = await response.Content.ReadAsStringAsync(cancellationToken); |
| 88 | + |
| 89 | + // INCORRECT - Resource leak |
| 90 | + var response = await httpClient.GetAsync(url, cancellationToken); |
| 91 | + if (!response.IsSuccessStatusCode) { return null; } |
| 92 | + var content = await response.Content.ReadAsStringAsync(cancellationToken); |
| 93 | + ``` |
44 | 94 |
|
45 | 95 | ### Output and Logging |
46 | 96 | - No emojis or special characters in logs, output, or comments |
|
0 commit comments