CommunityCoding & Developmentgithub.com

quality-testing

Backend unit-test conventions with xUnit, Moq and FluentAssertions: AAA structure, handler isolation, naming, validator and DelegatingHandler tests, coverage targets, and architecture tests. Use when writing or editing C# tests in the solution's test project.

What is quality-testing?

quality-testing is a Claude Code agent skill that backend unit-test conventions with xUnit, Moq and FluentAssertions: AAA structure, handler isolation, naming, validator and DelegatingHandler tests, coverage targets, and architecture tests. Use when writing or editing C# tests in the solution's test project.

Works with~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/19mittal/dotnet-next-toolkit/tree/HEAD/plugins/dotnet-backend/skills/quality-testing

Installed? Explore more Coding & Development skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Ask in your favorite AI

Open a new chat with this agent skill pre-loaded.

Documentation

Quality & Testing


0. Project context

Resolve once per session, from the working directory: the solution (*.sln / *.slnx, else *.csproj — ask if several match) and its projects by role: <Api>, <Application>, <Core>, <Infrastructure>, <Tests>. Those placeholders mean the real project names; paths below are relative to the solution root. Take product names from the repo — never invent one. If the solution is not layered this way, say so and ask before imposing this structure.


1. Framework Stack

ToolVersionRole
xUnitv3 (xunit.v3.mtp-v2)Test framework — [Fact], [Theory]; v3 on Microsoft.Testing.Platform needs OutputType=Exe
Moq4.20+Mock all external dependencies
FluentAssertions8.xReadable, expressive assertions
NullLogger<T>Microsoft.Extensions.Logging.AbstractionsSilent logger — never mock ILogger manually

Versions are what this skill was written against — the repo's own package versions win. For xUnit v3 on Microsoft.Testing.Platform the test project needs xunit.v3.mtp-v2, xunit.runner.visualstudio, Microsoft.NET.Test.Sdk, and Microsoft.Testing.Extensions.CodeCoverage (replaces coverlet.collector), and the solution global.json needs "test": { "runner": "Microsoft.Testing.Platform" }. If the repo is on xUnit v2, keep it there.

Never use Assert.Equal / Assert.Throws from xUnit directly — always use FluentAssertions (result.Should()...).

No MSTest, NUnit, or alternate assertion libraries for new tests.


2. Project Structure

tests/
  <Tests>/
    Common/
      TestHelpers.cs          ← TestEntityBuilder + MockUnitOfWork
    Handlers/
      <Context>/              ← one folder per Application feature context
    Infrastructure/           ← DelegatingHandler, Refit client tests
    Validators/               ← FluentValidation unit tests

Mirror Application feature folders. One test class per handler (or cohesive group). Shared builders/fakes in Common/ — avoid duplication in Arrange blocks.

MockUnitOfWork and TestEntityBuilder are this skill's names for two shared helpers: a Mock<IUnitOfWork> wrapper that hands out one Mock<IRepository<T>> per entity type, and a builder of valid default entities. If the repo has equivalents under other names, use those; if it has none, create them once in Common/ rather than re-mocking in every test.


3. Test Class Structure — Mandatory Template

public class <HandlerName>Tests
{
    // ── Dependencies ──────────────────────────────────────────────────────
    private readonly MockUnitOfWork _uow;
    private readonly Mock<IDependency> _mockDep;
    private readonly <HandlerName> _handler;

    public <HandlerName>Tests()
    {
        _uow = new MockUnitOfWork();
        _mockDep = new Mock<IDependency>();
        _handler = new <HandlerName>(
            _uow.Object,
            _mockDep.Object,
            TestEntityBuilder.NullLogger<<HandlerName>>());
    }

    [Fact]
    public async Task Handle_<Scenario>_<ExpectedResult>()
    {
        // Arrange
        ...

        // Act
        var result = await _handler.Handle(command, CancellationToken.None);

        // Assert
        result.Should().NotBeNull();
        result.Field.Should().Be(expectedValue);
    }
}

4. Naming Convention — Strict

Format: MethodName_Scenario_ExpectedResult

✅ Handle_ValidCommand_ReturnsOrderResponse
✅ Handle_CustomerNotFound_ThrowsNotFoundException
✅ Handle_FifthFailedAttempt_SetsLockoutEnd
✅ SendAsync_InnerHandlerThrows_LogsFailureAndRethrows
✅ LoginValidator_EmptyEmail_ContainsEmailError

❌ TestLogin
❌ SuccessCase
❌ HandlerTest1

5. AAA Pattern — Mandatory Structure

Every test method must contain exactly three clearly commented sections:

// Arrange — set up mocks, entities, and the command/query under test
var entity = TestEntityBuilder.BuildActive<Order>();
_uow.Repository<Order>().Setup(r => r.SingleOrDefaultAsync(...)).ReturnsAsync(entity);

// Act — execute the handler or validator once
var result = await _handler.Handle(command, CancellationToken.None);

// Assert — use FluentAssertions exclusively
result.Should().NotBeNull();
result.AccessToken.Should().NotBeEmpty();

One logical behavior per test.


6. Isolation Rules — No Real Infrastructure

What to mockHow
IUnitOfWork + all repositoriesUse MockUnitOfWork from Common/TestHelpers.cs
ILogger<T>TestEntityBuilder.NullLogger<T>() — NullLogger<T>.Instance
IMapper (Mapster)new Mock<IMapper>() — setup .Map<T>() with .Returns(...)
Core service interfacesnew Mock<IPaymentGatewayService>() etc.
HttpMessageHandlerUse FakeInnerHandler : HttpMessageHandler subclass
IHttpContextAccessornew Mock<IHttpContextAccessor>()

Absolutely forbidden in unit tests:

  • new AppDbContext(...) — no real DB connections
  • new HttpClient(...) with real network calls
  • Thread.Sleep / Task.Delay > 100ms (except 50ms for DelegatingHandler log assertions)
  • Any [Collection] that shares mutable static state

Test handlers and domain logic in isolation — not controllers, not real HTTP, not real database.


7. High-Value Test Patterns

Capture a mutated entity with a Callback and assert on it; verify SaveChangesAsync was called exactly once (atomicity) and never when a guard throws; drive state machines with [Theory]; make a mocked dependency throw to prove failure propagation. Cover validation failures, empty input, boundary values, downstream failures and cancellation in command handlers. Code for each: reference/test-patterns.md.


8. DelegatingHandler Testing Pattern

Test a DelegatingHandler through a fake inner HttpMessageHandler and an HttpMessageInvoker — never mock HttpClient. Template: reference/test-patterns.md.


9. Validator Testing

Validators are pure functions: test them synchronously, without mocks, and assert on the specific property name that failed — never IsValid alone. Template: reference/test-patterns.md.


10. Coverage Targets (by Handler Type)

Handler CategoryMinimum Test Cases
Auth Handlers6+ (success, unknown user, locked, inactive, wrong password, lockout trigger)
Command Handlers4+ (success, each guard failure, atomicity verification)
Query Handlers2+ (returns data, returns empty/not-found)
Validators2+ per field with constraints (valid + each invalid variant)
DelegatingHandlers5+ (success log, failure log, header injection, exception rethrow, logging-failure absorption)

Defer to integration tests only when explicitly requested; default to unit tests per this rule.


11. Architecture tests and running the suite

Architecture tests pin layer direction and module boundaries; a baseline of accepted violations only ever shrinks. Use the repo's own test command — if dotnet test reports zero tests on Microsoft.Testing.Platform, run the built test executable. Unit tests cannot see a missing DI registration, so start every host after changing a constructor dependency. Details: reference/architecture-tests-and-running.md.


Checklist Before Completing Work

  • xUnit + Moq + FluentAssertions only
  • AAA structure with comments separating sections
  • External dependencies mocked via MockUnitOfWork and Core interface mocks
  • Command handler edge cases covered (invalid input, failures, boundaries, atomicity)
  • Assertions use FluentAssertions, not classic Assert.*
  • Test names follow MethodName_Scenario_ExpectedResult
  • Architecture tests green; any accepted-violation baseline did not grow

Individual skills in this repo

This repo contains 4 individual skills — each has its own dedicated page.

Related Skills