Org Skills

dotnet-testing

Design a .NET test strategy and write the tests — xUnit v3 conventions, unit tests of domain logic, ASP.NET Core integration tests with WebApplicationFactory and Testcontainers, a test authentication handler, faking outbound HTTP, resetting data between tests, mocking only what you do not own, contract and architecture tests, coverage, flaky-test triage and CI.

Download .zip Raw Source
When agents use itUse this whenever the user asks how to test a C# class, handler, minimal API endpoint, DbContext, message consumer or BackgroundService; creates a *.Tests.csproj; sets up WebApplicationFactory, Testcontainers, Respawn or FakeTimeProvider; migrates from xUnit v2 to v3 or from VSTest to Microsoft.Testing.Platform; asks about mocking ILogger, HttpClient or DbContext, whether the EF InMemory provider is acceptable, code coverage, dotnet test in CI, or "what should I test". Also use it when a test passes locally and fails in CI.

Install

Copilot (VS Code, Visual Studio, Copilot CLI and github.com) reads skills from the repository — commit them so the whole team gets them.

npx skills add AGCO-Global/org-skills --skill dotnet-testing -a github-copilot
# or with the org installer (adds .github/skills/dotnet-testing):
npx -y github:AGCO-Global/org-skills add skill dotnet-testing

Uses the open skills CLI. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, OpenCode, Windsurf and 60+ others — it asks which agent to install into.

npx skills add AGCO-Global/org-skills --skill dotnet-testing
# user-level instead of project-level:
npx skills add AGCO-Global/org-skills --skill dotnet-testing -g

Installs the backend-dotnet-skills plugin, which bundles all Backend / .NET skills and keeps them updated.

/plugin marketplace add AGCO-Global/org-skills
/plugin install backend-dotnet-skills@org-skills
# or just this skill, in this repository:
npx skills add AGCO-Global/org-skills --skill dotnet-testing -a claude-code

Use Download .zip above, then upload it under Customize → Skills → Upload skill. Team and Enterprise admins can sync this repo as a plugin marketplace instead.

Installs into .agents/skills/, which Codex reads.

npx skills add AGCO-Global/org-skills --skill dotnet-testing -a codex

Installs into Cursor's skills folder.

npx skills add AGCO-Global/org-skills --skill dotnet-testing -a cursor

Installs into Gemini CLI's skills folder.

npx skills add AGCO-Global/org-skills --skill dotnet-testing -a gemini-cli

Nothing to install. Press Download .zip above, unzip it, and drop the dotnet-testing folder into your tool's skills folder — .claude/skills/, .github/skills/, .cursor/skills/ or .agents/skills/. Step-by-step, per tool: How to use it. For any other tool with rules or custom prompts, Copy SKILL.md and paste it in — it is plain Markdown.

The npx commands need Node.js 20+ and use your normal git sign-in to GitHub, so they work while the repository is private. Without Node.js, see the No Node.js tab — a skill is a folder of Markdown, so copying it in works just as well.

Skill contents

.NET Testing

Targets: .NET 10 LTS, xUnit v3, EF Core 10, Testcontainers for .NET (xUnit v2 and EF Core 8 noted where different) · Verified: 2026-09 against https://xunit.net/docs/getting-started/v3/migration and https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-10.0

Tests exist so the team can refactor and upgrade .NET versions without fear. Optimise for confidence per minute of maintenance: exercise behaviour through public seams against real infrastructure where that is cheap, and fake only what you do not own. A test that mocks everything it touches proves the mocks work.

1. Decide first

Question Default Change when
Which layer for this behaviour? Domain rule → unit; anything that crosses HTTP, DI, EF or serialisation → integration at the HTTP boundary A bug slipped through: write the test at the layer that would have caught it
Framework xUnit v3 for new projects (xunit.v3 packages) The repository already uses NUnit or MSTest — stay consistent
Runner dotnet test VSTest mode (still the SDK default) New solution on the .NET 10 SDK → opt into Microsoft.Testing.Platform (references/runner-and-ci.md)
Database in tests Testcontainers with the real engine A pure algorithm needs no database at all
EF InMemory provider No Never — it is not relational and Microsoft advises against it for testing
Mocking Fake what you do not own: third-party HTTP, email, the clock Your own domain types, DbContext, IOptions<T>, ILogger<T> are never mocked
Assertions Built-in Assert, or Shouldly FluentAssertions v8+ needs a commercial licence; v7 stays Apache 2.0
Time TimeProvider injected, FakeTimeProvider.Advance() in tests Never DateTime.UtcNow or Thread.Sleep

2. What each layer is for

Layer Tooling Catches
Static Nullable + warnings-as-errors, analyzers Null bugs, API misuse — free, before any test runs
Unit xUnit + builders Invariants, state transitions, boundaries of aggregates and value objects
Integration (in-process) WebApplicationFactory + Testcontainers Routing, auth, validation, DI wiring, EF translation, serialisation
Contract PactNet, OpenAPI diff, message schema snapshots Breaking a consumer without noticing
Architecture NetArchTest / ArchUnitNET Boundary decay (dotnet-architecture)
End-to-end HTTP or Playwright smoke against a deployed environment A handful of critical journeys only

Push toward integration tests at the HTTP boundary for an ASP.NET Core service: they catch the class of bug that unit tests with mocks structurally cannot.

3. Unit tests of domain logic

using Xunit;

[Fact]
public void Cancel_ShippedOrder_Throws()
{
    var order = new OrderBuilder().Shipped().Build();

    var act = () => order.Cancel("changed mind");

    var ex = Assert.Throws<DomainException>(act);
    Assert.Contains("shipped", ex.Message);
}

Name the test after the behaviour (Method_Condition_Outcome). Use [Theory] with [InlineData] for input tables. Builders with sensible defaults (new OrderBuilder().WithLines(3).Build()) keep tests readable and survive constructor changes; keep the values the test asserts on explicit in the test. Do not unit-test framework glue — endpoint mapping and EF configuration belong to §4.

4. Integration tests with WebApplicationFactory

Package Microsoft.AspNetCore.Mvc.Testing. This fixture is the most copied code in any .NET repository, so get the version details right:

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Testcontainers.PostgreSql;
using Xunit;

public sealed class ApiFactory : WebApplicationFactory<Program>, IAsyncLifetime
{
    private readonly PostgreSqlContainer _db =
        new PostgreSqlBuilder().WithImage("postgres:17-alpine").Build();

    public async ValueTask InitializeAsync()
    {
        await _db.StartAsync();
        using var scope = Services.CreateScope();
        await scope.ServiceProvider.GetRequiredService<OrdersDbContext>().Database.MigrateAsync();
    }

    public override async ValueTask DisposeAsync()
    {
        await base.DisposeAsync();
        await _db.DisposeAsync();
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder) =>
        builder.UseEnvironment("Testing").ConfigureTestServices(services =>
        {
            // EF Core 9+ registers this alongside DbContextOptions<T>; removing only
            // DbContextOptions<T> leaves the original provider and the second UseNpgsql throws.
            services.RemoveAll<IDbContextOptionsConfiguration<OrdersDbContext>>();
            services.AddDbContext<OrdersDbContext>(o => o.UseNpgsql(_db.GetConnectionString()));
        });
}

On xUnit v2, IAsyncLifetime members return Task and you cannot override DisposeAsync; on EF Core 8, remove DbContextOptions<OrdersDbContext> instead. Mixing the two conventions is why so many copies of this class do not compile.

  • Replace only true externals in ConfigureTestServices: payment gateways, email, message transport, the clock.
  • Issue test identities with a test authentication handler rather than switching authorisation off — otherwise the tests never exercise the policies (references/integration-fixture.md).
  • Assert on status code, the ProblemDetails body and the resulting database row. Not on internal calls.
  • Reset data between tests (Respawn, a rollback transaction, or a schema per collection) and never rely on test order.

5. Mocking — and when not to

  • Libraries: NSubstitute or Moq, whichever the repository already uses; FakeItEasy is fine too.
  • Fake at the boundary you do not own: outbound HTTP through a stub HttpMessageHandler or WireMock.Net, message transport through the broker library's test harness (MassTransit's ITestHarness), email and SMS.
  • Never mock DbContext or DbSet — you end up asserting LINQ-to-objects, which translates differently from LINQ-to-SQL. Use Options.Create(...) for IOptions<T>, NullLogger<T> for logging, FakeLogger<T> when the log line is the behaviour.
  • Assert interactions only when the interaction is the behaviour (a message was published). Otherwise assert outcomes.

6. Deliverable format

## Behaviours      happy path, validation, authorisation, not found, concurrency, edge cases
## Layer per case  where each one is tested, and why that layer
## Tests           complete classes plus any fixture or builder additions, reusing what exists
## Run             the command, and prerequisites (Docker for Testcontainers)

Checklist

  • Behaviours listed before any test code was written.
  • Each test names the behaviour it asserts, and asserts one.
  • Integration tests hit the real pipeline with a real database engine.
  • Authorisation is exercised with a test identity, not disabled.
  • Data is reset between tests; no test depends on another's rows or order.
  • No mocked DbContext, no EF InMemory provider.
  • Time is controlled through TimeProvider; no Thread.Sleep.
  • Every async test awaits everything and passes a cancellation token to I/O.
  • The fixture matches the project's xUnit and EF Core majors.
  • Assertion library licence checked before adding or upgrading it.

Anti-patterns

  • Mocking DbContext/DbSet, or the EF InMemory provider → Testcontainers with the real engine.
  • Disabling authentication in integration tests → a test authentication handler issuing claims per test.
  • Asserting "no exception was thrown" → assert the observable outcome, including the database state.
  • Verifying every mock call → assert outcomes; verify only interactions that are the behaviour.
  • Thread.Sleep to wait for something → FakeTimeProvider.Advance() or poll with a deadline.
  • One [Fact] covering five behaviours → one behaviour per test, [Theory] for input tables.
  • Testing private methods by reflection → test through the public seam, or the design is wrong.
  • Coverage chased with assertion-free tests → gate on changed-line coverage and review the tests.
  • A skipped test with no owner or issue link → delete it or fix it; a permanent skip is a lie in the report.

Go deeper

  • references/integration-fixture.md — the test authentication handler, Respawn reset, stub HttpMessageHandler and WireMock.Net, MassTransit ITestHarness, testing a BackgroundService, FakeTimeProvider, and Aspire.Hosting.Testing when the app host owns the dependencies.
  • references/runner-and-ci.md — VSTest versus Microsoft.Testing.Platform mode with the coverage command for each, the CI pipeline shape, the flaky-test triage table, Verify snapshots, PactNet and Stryker.NET mutation testing.
  • Sibling skills: dotnet-development for the code under test, dotnet-architecture for architecture tests, dotnet-performance for load and benchmark work, database-migrations for migration tests, backend-code-review for reviews.

References

Deeper material the agent loads only when needed.