Dotnet testing xunit

From makifbaysal/tasktrooper · View interactive version

Dotnet testing xunit is an AI agent skill from the GitHub repository makifbaysal/tasktrooper. Use when writing tests for C#/.NET code - xUnit structure, NSubstitute or the repository's mocking library at ports, WebApplicationFactory for HTTP, Testcontainers Postgres for EF Core, FakeTimeProvider, test-first

How to use this skill

Skill file

.NET Testing (xUnit)

Overview

Test-first in C#, same discipline as everywhere (see tdd-workflow): write the failing test, watch it fail, minimal code to pass. This skill is the .NET mechanics for that cycle.

Core principle: unit-test the domain and services as plain C# without starting the host. Start the host (WebApplicationFactory) only where wiring, serialization, validation or SQL is what you are proving.

Test levels

| Level | What it covers | Tools |

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

| Unit | Domain entity / value object, no mocks | xUnit [Fact] / [Theory] |

| Unit with fakes | Application service, its ports faked | xUnit + NSubstitute (or the repository's Moq / FakeItEasy) |

| Persistence | Repository / DbContext queries against real Postgres | Testcontainers PostgreSqlContainer + the repository's migrations |

| HTTP | Endpoint wiring, binding, validation, ProblemDetails, auth | WebApplicationFactory<Program> (Microsoft.AspNetCore.Mvc.Testing) + HttpClient |

Most tests are the first two. Match the repository's framework: xUnit (v3 for new projects; v2 where the repository is on it), NUnit or MSTest — never add a second one.

Unit test with a faked port

public sealed class TaskServiceTests
{
    private readonly ITaskRepository _repo = Substitute.For<ITaskRepository>();
    private readonly FakeTimeProvider _clock = new(DateTimeOffset.Parse("2026-01-01T00:00:00Z"));
    private readonly TaskService _service;

    public TaskServiceTests() => _service = new TaskService(_repo, _clock);

    [Fact]
    public async Task Create_persists_and_returns_the_task()
    {
        var task = await _service.CreateAsync("Write the report", CancellationToken.None);

        Assert.Equal("Write the report", task.Title);
        await _repo.Received(1).AddAsync(task, Arg.Any<CancellationToken>());
    }

    [Theory]
    [InlineData("")]
    [InlineData("   ")]
    public async Task Create_rejects_a_blank_title(string title)
    {
        await Assert.ThrowsAsync<InvalidTaskTitleException>(() => _service.CreateAsync(title, CancellationToken.None));
        await _repo.DidNotReceiveWithAnyArgs().AddAsync(default!, default);
    }
}

Rules

Common Mistakes

Red Flags

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.