Dotnet testing

From macalbert/envilder · View interactive version

Dotnet testing is an AI agent skill from the GitHub repository macalbert/envilder. Mandatory testing conventions for .NET (xUnit, AwesomeAssertions). Use for unit, integration, or acceptance tests with xUnit, Testcontainers, or Playwright.

How to use this skill

Skill file

Testing Conventions (.NET)

This skill defines the MANDATORY testing conventions for .NET projects.

These are rules, not guidelines.


Documentation Rules

NO Comments Except AAA Markers


Libraries

| Category | Library | Purpose |

| -------- | ------- | ------- |

| Framework | xUnit | Test framework |

| Assertions | AwesomeAssertions | Fluent assertion syntax |

| Snapshots | Verify.Xunit | Snapshot / approval testing |

| Mocking | NSubstitute | Spies, stubs, and mocks |

| Mocking (HTTP) | WireMock.Net | HTTP service mocking |

| Test data (fake) | Bogus | Realistic fake data (Mother pattern) |

| Test data (dummy) | AutoFixture | Automatic dummy object generation |

| Containers | Testcontainers | Docker containers in tests |


Core Principles

1. AAA Pattern (Arrange – Act – Assert)

ALL tests MUST follow the AAA pattern, separated by inline comments.

Rules

per test**: if you need two actions or two asserts, write two tests

if they are genuinely part of the same logical action (rare and exceptional).

Two independent operations = two tests.

If you need a precondition check, extract it to a separate test or use a

guard clause that throws: not an assertion.

static completeness checks, and data validation tests. No exceptions.

IDisposable for teardown

xUnit Example
[Fact(Timeout = CancellationTokenForTest.ShortTimeout)]
public async Task Should_CreateGroup_When_RequestIsValid()
{
    // Arrange
    var request = new CreateGroupRequest { Name = "Test Group" };
    var command = new CreateGroupCommand(request);

    // Act
    var actual = await _sut.Handle(command, CancellationToken.None);

    // Assert
    actual.Should().NotBeNull();
    actual.GroupId.Should().NotBeEmpty();
    _repository.Received(1).AddGroup(Arg.Any<Group>());
}

2. Test Naming Convention

Should_{ExpectedBehavior}_When_{Condition}
Rules

3. Variable Naming (MANDATORY)

| Purpose | Name |

| ------- | ---- |

| Subject under test | _sut (field) or sut (local) |

| Expected value | expected |

| Actual result | actual |


Test Class Structure

public class CreateGroupCommandHandlerTests
{
    private readonly Fixture _fixture;
    private readonly IEnvilderRepository _repository;
    private readonly CreateGroupCommandHandler _sut;

    public CreateGroupCommandHandlerTests()
    {
        _fixture = new();
        _repository = Substitute.For<IEnvilderRepository>();
        _sut = new(_repository);
    }
}

Exception Testing

Act and Assert MUST be separate.

✅ CORRECT

[Fact(Timeout = CancellationTokenForTest.ShortTimeout)]
public async Task Should_ThrowNotFound_When_GroupDoesNotExist()
{
    // Arrange
    _repository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
        .Returns((Group?)null);

    // Act
    var act = () => _sut.Handle(query, CancellationToken.None);

    // Assert
    await act.Should().ThrowAsync<NotFoundException>();
}

❌ FORBIDDEN

// Act & Assert   ← NEVER
await Assert.ThrowsAsync<NotFoundException>(
    () => _sut.Handle(query, CancellationToken.None));

Teardown & Cleanup

Never use try/finally in tests. Use framework mechanisms:

| Scenario | Mechanism |

| -------- | --------- |

| Async setup/teardown | IAsyncLifetime (InitializeAsync / DisposeAsync) |

| Sync cleanup | IDisposable (Dispose) |

| Shared fixture | IAsyncLifetime on collection fixture |

public class MyTests : IAsyncLifetime
{
    private (string Name, string? Value)[] _originalEnvValues = [];

    public Task InitializeAsync()
    {
        _originalEnvValues = EnvVarNames
            .Select(v => (Name: v, Value: Environment.GetEnvironmentVariable(v)))
            .ToArray();
        return Task.CompletedTask;
    }

    public Task DisposeAsync()
    {
        foreach (var (name, value) in _originalEnvValues)
        {
            Environment.SetEnvironmentVariable(name, value);
        }
        return Task.CompletedTask;
    }
}

Verification Commands

| Context | Command |

| ------- | ------- |

| Unit tests | dotnet test tests/sdks/dotnet/ --filter "Category!=Acceptance" |

| Acceptance (Docker) | dotnet test tests/sdks/dotnet/ |

| Format check | dotnet format src/sdks/dotnet/Envilder.sln --verify-no-changes |


Completion Criteria

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.