|
| 1 | +--- |
| 2 | +applyTo: "**/*Tests.cs,**/*Test.cs,**/*.Tests/**/*.cs" |
| 3 | +description: "Unit testing guidelines for Bicep local-deploy extension handlers" |
| 4 | +--- |
| 5 | + |
| 6 | +# Unit Testing Guidelines for Bicep Extensions |
| 7 | + |
| 8 | +## Project Setup |
| 9 | +- Use MSTest as the test framework |
| 10 | +- Use Moq for mocking dependencies |
| 11 | +- Use FluentAssertions for readable assertions |
| 12 | +- Target .NET 9 |
| 13 | + |
| 14 | +## Test Project Structure |
| 15 | +```xml |
| 16 | +<ItemGroup> |
| 17 | + <PackageReference Include="Microsoft.NET.Test.Sdk" /> |
| 18 | + <PackageReference Include="MSTest.TestAdapter" /> |
| 19 | + <PackageReference Include="MSTest.TestFramework" /> |
| 20 | + <PackageReference Include="Moq" /> |
| 21 | + <PackageReference Include="FluentAssertions" /> |
| 22 | +</ItemGroup> |
| 23 | +``` |
| 24 | + |
| 25 | +## Handler testability |
| 26 | + |
| 27 | +### Dependency Injection Pattern |
| 28 | +- **Always** abstract external dependencies (HTTP clients, file systems, APIs) behind interfaces |
| 29 | +- Inject dependencies via constructor |
| 30 | +- Avoid direct access to external resources in handlers |
| 31 | + |
| 32 | +❌ **Avoid** - Hard to test: |
| 33 | +```csharp |
| 34 | +public class MyHandler : TypedResourceHandler<MyProperties, MyIdentifiers> |
| 35 | +{ |
| 36 | + protected override Task<ExtensibilityOperationSuccessResponse> CreateOrUpdate(...) |
| 37 | + { |
| 38 | + // Direct dependency - can't test without real external system |
| 39 | + var client = new HttpClient(); |
| 40 | + // ... |
| 41 | + } |
| 42 | +} |
| 43 | +``` |
| 44 | + |
| 45 | +✅ **Prefer** - Testable with mocks: |
| 46 | +```csharp |
| 47 | +public class MyHandler : TypedResourceHandler<MyProperties, MyIdentifiers> |
| 48 | +{ |
| 49 | + private readonly IMyService _service; |
| 50 | + |
| 51 | + public MyHandler(IMyService service) |
| 52 | + { |
| 53 | + _service = service; |
| 54 | + } |
| 55 | + |
| 56 | + protected override async Task<ExtensibilityOperationSuccessResponse> CreateOrUpdate(...) |
| 57 | + { |
| 58 | + await _service.DoWorkAsync(...); |
| 59 | + return CreateSuccessResponse(properties, identifiers); |
| 60 | + } |
| 61 | +} |
| 62 | +``` |
| 63 | + |
| 64 | +## Test Class structure |
| 65 | + |
| 66 | +```csharp |
| 67 | +[TestClass] |
| 68 | +public class MyHandlerTests |
| 69 | +{ |
| 70 | + private Mock<IMyService> _mockService = null!; |
| 71 | + private MyHandler _handler = null!; |
| 72 | + |
| 73 | + [TestInitialize] |
| 74 | + public void Setup() |
| 75 | + { |
| 76 | + // Use strict behavior to fail on unexpected calls |
| 77 | + _mockService = new Mock<IMyService>(MockBehavior.Strict); |
| 78 | + _handler = new MyHandler(_mockService.Object); |
| 79 | + } |
| 80 | + |
| 81 | + [TestCleanup] |
| 82 | + public void Cleanup() |
| 83 | + { |
| 84 | + // Verify all setups were invoked |
| 85 | + _mockService.VerifyAll(); |
| 86 | + } |
| 87 | +} |
| 88 | +``` |
| 89 | + |
| 90 | +## Test naming convention |
| 91 | +- Use descriptive names: `MethodName_Scenario_ExpectedResult` |
| 92 | +- Examples: |
| 93 | + - `CreateOrUpdate_WhenResourceExists_UpdatesResource` |
| 94 | + - `Get_WhenResourceNotFound_ThrowsNotFoundException` |
| 95 | + - `Delete_RemovesResourceSuccessfully` |
| 96 | + |
| 97 | +## Arrange-Act-Assert Pattern |
| 98 | +- **Arrange**: Set up mocks and test data |
| 99 | +- **Act**: Call the method under test |
| 100 | +- **Assert**: Verify the result |
| 101 | + |
| 102 | +```csharp |
| 103 | +[TestMethod] |
| 104 | +public async Task CreateOrUpdate_WritesResourceAndReturnsSuccess() |
| 105 | +{ |
| 106 | + // Arrange |
| 107 | + var properties = new MyProperties { Name = "Test" }; |
| 108 | + var identifiers = new MyIdentifiers { Id = "123" }; |
| 109 | + |
| 110 | + _mockService |
| 111 | + .Setup(s => s.CreateAsync(identifiers.Id, properties.Name, It.IsAny<CancellationToken>())) |
| 112 | + .Returns(Task.CompletedTask); |
| 113 | + |
| 114 | + // Act |
| 115 | + var response = await _handler.CreateOrUpdate(properties, identifiers, CancellationToken.None); |
| 116 | + |
| 117 | + // Assert |
| 118 | + response.Should().NotBeNull(); |
| 119 | + response.Resource.Should().NotBeNull(); |
| 120 | +} |
| 121 | +``` |
| 122 | + |
| 123 | +## Testing exceptions |
| 124 | + |
| 125 | +```csharp |
| 126 | +[TestMethod] |
| 127 | +public async Task CreateOrUpdate_WhenServiceFails_ThrowsException() |
| 128 | +{ |
| 129 | + // Arrange |
| 130 | + _mockService |
| 131 | + .Setup(s => s.CreateAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())) |
| 132 | + .ThrowsAsync(new InvalidOperationException("Service unavailable")); |
| 133 | + |
| 134 | + // Act & Assert |
| 135 | + await FluentActions |
| 136 | + .Invoking(() => _handler.CreateOrUpdate(properties, identifiers, CancellationToken.None)) |
| 137 | + .Should() |
| 138 | + .ThrowAsync<InvalidOperationException>() |
| 139 | + .WithMessage("Service unavailable"); |
| 140 | +} |
| 141 | +``` |
| 142 | + |
| 143 | +## Data-Driven tests |
| 144 | +Use `[DataRow]` for testing multiple scenarios: |
| 145 | + |
| 146 | +```csharp |
| 147 | +[TestMethod] |
| 148 | +[DataRow("project1", "Description 1")] |
| 149 | +[DataRow("project-with-dashes", "Another description")] |
| 150 | +[DataRow("ProjectWithCaps", "")] |
| 151 | +public async Task CreateOrUpdate_HandlesVariousInputs(string name, string description) |
| 152 | +{ |
| 153 | + // Test implementation |
| 154 | +} |
| 155 | +``` |
| 156 | + |
| 157 | +## Testing Strategy by component |
| 158 | + |
| 159 | +| Component | What to Test | Approach | |
| 160 | +|-----------|--------------|----------| |
| 161 | +| **Handlers** | Business logic, validation, error handling | Mock all dependencies | |
| 162 | +| **Services** | External integrations, API calls | Isolated test environments | |
| 163 | +| **Validators** | Input validation rules | Direct instantiation | |
| 164 | + |
| 165 | +## Service integration tests |
| 166 | +For services that interact with external systems, use isolated test environments: |
| 167 | + |
| 168 | +```csharp |
| 169 | +[TestClass] |
| 170 | +public class MyServiceTests |
| 171 | +{ |
| 172 | + private string _testDirectory = null!; |
| 173 | + |
| 174 | + [TestInitialize] |
| 175 | + public void Setup() |
| 176 | + { |
| 177 | + _testDirectory = Path.Combine(Path.GetTempPath(), $"test_{Guid.NewGuid()}"); |
| 178 | + Directory.CreateDirectory(_testDirectory); |
| 179 | + } |
| 180 | + |
| 181 | + [TestCleanup] |
| 182 | + public void Cleanup() |
| 183 | + { |
| 184 | + if (Directory.Exists(_testDirectory)) |
| 185 | + { |
| 186 | + Directory.Delete(_testDirectory, recursive: true); |
| 187 | + } |
| 188 | + } |
| 189 | +} |
| 190 | +``` |
| 191 | + |
| 192 | +## Running tests |
| 193 | + |
| 194 | +```powershell |
| 195 | +# Run all tests |
| 196 | +dotnet test |
| 197 | +
|
| 198 | +# Run with detailed output |
| 199 | +dotnet test --logger "console;verbosity=detailed" |
| 200 | +
|
| 201 | +# Run specific test class |
| 202 | +dotnet test --filter "FullyQualifiedName~MyHandlerTests" |
| 203 | +
|
| 204 | +# Run with code coverage |
| 205 | +dotnet test --collect:"XPlat Code Coverage" |
| 206 | +``` |
| 207 | + |
| 208 | +## Common FluentAssertions Patterns |
| 209 | + |
| 210 | +```csharp |
| 211 | +// Null checks |
| 212 | +result.Should().NotBeNull(); |
| 213 | +result.Should().BeNull(); |
| 214 | + |
| 215 | +// Object comparison |
| 216 | +result.Should().BeEquivalentTo(expected); |
| 217 | + |
| 218 | +// Collection assertions |
| 219 | +results.Should().HaveCount(3); |
| 220 | +results.Should().Contain(item); |
| 221 | + |
| 222 | +// String assertions |
| 223 | +message.Should().StartWith("Error:"); |
| 224 | +message.Should().Contain("not found"); |
| 225 | +``` |
| 226 | + |
| 227 | +## Key principles |
| 228 | + |
| 229 | +1. **Use Dependency Injection** — Abstract external dependencies behind interfaces |
| 230 | +2. **Apply Loose Coupling** — Handlers depend on abstractions, not implementations |
| 231 | +3. **Use Strict Mocking** — Fail on unexpected calls to catch bugs early |
| 232 | +4. **Test One Scenario Per Method** — Keep tests focused and readable |
| 233 | +5. **Verify All Mocks** — Ensure all expected calls were made |
0 commit comments