본문으로 건너뛰기
cccskills
무료GitHub에 공개

dotnet-testing-xunit

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

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

연동 도구PostgreSQL
설치 방법 보기

포함된 파일(1)

  • SKILL.md5.0 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

.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

LevelWhat it coversTools
UnitDomain entity / value object, no mocksxUnit [Fact] / [Theory]
Unit with fakesApplication service, its ports fakedxUnit + NSubstitute (or the repository's Moq / FakeItEasy)
PersistenceRepository / DbContext queries against real PostgresTestcontainers PostgreSqlContainer + the repository's migrations
HTTPEndpoint wiring, binding, validation, ProblemDetails, authWebApplicationFactory<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

  • Fake ports, never the class under test. Assert on the returned value or the observable state first; Received(...) alone proves only that the fake was called.
  • One behaviour per test, named for it (Create_rejects_a_blank_title). [Theory] + [InlineData] / [MemberData] for boundary tables (200 characters accepted, 201 rejected).
  • Time is injected: TimeProvider in production code, FakeTimeProvider (Microsoft.Extensions.TimeProvider.Testing) in tests — never DateTime.Now in either.
  • Real Postgres, not the InMemory provider or SQLite, for anything that runs SQL: the InMemory provider ignores constraints, transactions and SQL translation. One container per test class or collection (IAsyncLifetime / a collection fixture), migrations applied once, data reset between tests (Respawn, or a transaction rolled back per test).
  • HTTP tests go through WebApplicationFactory<Program> with ConfigureTestServices replacing only the external dependencies (payment gateway, clock), not the services under test. Assert the status code AND the body shape (ProblemDetails type/errors). On .NET 9 or earlier a top-level-statement Program needs public partial class Program; for the factory to see it.
  • Assertions: the repository's library. Do not add FluentAssertions to a project that lacks it — version 8 is commercially licensed; plain Assert, Shouldly or AwesomeAssertions are the free options. Do not add Moq to a project that uses NSubstitute or the other way round.
  • async tests return Task, never async void; pass TestContext.Current.CancellationToken (xUnit v3) where the API takes one.
  • Focused run while iterating: dotnet test --filter "FullyQualifiedName~TaskServiceTests"; the whole dotnet test before you stop. Coverage through the repository's collector (coverlet --collect:"XPlat Code Coverage" or Microsoft.Testing.Platform --coverage); mutation testing, where the repository runs it, is Stryker.NET.

Common Mistakes

  • Testing EF queries against the InMemory provider and shipping SQL that Postgres rejects.
  • A WebApplicationFactory test for every service rule — slow, and it hides design problems a plain unit test would show.
  • Thread.Sleep / Task.Delay to wait for time to pass instead of advancing FakeTimeProvider.
  • Shared static state between test classes run in parallel.

Red Flags

  • The test passes before the production code exists (it tests the fake).
  • A unit test that needs Docker.
  • [Fact(Skip = ...)] added to make the suite green.

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Use when writing acceptance criteria for a task - express each as an observable Given/When/Then that QA can execute, including negative cases

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

makifbaysal/tasktrooper1172026년 10월 18일 업데이트

Use when the diff adds or changes an endpoint, resolver, RPC, job or query that takes an object id, a role check, a request binding or a tenant filter - BOLA/IDOR, function-level authorization, mass assignment and tenant scoping

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

makifbaysal/tasktrooper1172026년 10월 18일 업데이트

Use on every UI change - semantic HTML, labels for controls, keyboard-navigable dialogs/menus, visible focus, and never color as the only signal

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

makifbaysal/tasktrooper1172026년 10월 18일 업데이트

Use when a task changes any screen, form, dialog, menu or control - Lighthouse/axe scan of the changed screens, a keyboard walk, and the thresholds that fail a task

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

makifbaysal/tasktrooper1172026년 10월 18일 업데이트

How to work a task returned with review, QA or UAT findings. Use when a task is in need_revision or PR review comments are in your context.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

makifbaysal/tasktrooper1172026년 10월 18일 업데이트

Use when the repository keeps its alerting in code, or a person asks for alerts outside TaskTrooper - PrometheusRule YAML, a Cloud Monitoring alert policy in Terraform, a Datadog monitor, each routed to TaskTrooper's alert ingest URL so it opens an incident here

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

makifbaysal/tasktrooper1172026년 10월 18일 업데이트

makifbaysal의 스킬 모두 보기

이 스킬의 문제 신고