Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
affaan-m avatar

Csharp Testing

  • 1.4k installs
  • 238k repo stars
  • Updated August 5, 2026
  • affaan-m/ecc

This is a copy of csharp-testing by affaan-m - installs and ranking accrue to the original listing.

csharp-testing is an agent skill that generates high-quality maintainable tests for C# and .NET services using xUnit, FluentAssertions, and modern mocking patterns.

About

csharp-testing is an ECC agent skill for comprehensive .NET test development using a six-tool stack: xUnit as the test framework, FluentAssertions for readable assertions, NSubstitute or Moq for mocking, Testcontainers for real infrastructure in integration tests, WebApplicationFactory for ASP.NET Core integration tests, and Bogus for realistic test data. The skill covers Arrange-Act-Assert unit structure, test infrastructure setup, coverage review, and debugging flaky or slow tests. Developers reach for csharp-testing when writing new C# tests, auditing test quality, or standing up .NET test projects. Triggers include new test authoring, test infrastructure configuration, and flaky test investigation for .NET APIs and services.

  • xUnit + FluentAssertions + NSubstitute/Moq test stack
  • Arrange-Act-Assert unit test structure with realistic examples
  • Integration test patterns using Testcontainers and WebApplicationFactory
  • Test data generation with Bogus for production-like scenarios
  • Guidance for reviewing test quality, coverage, and fixing flaky tests

Csharp Testing by the numbers

  • 1,375 all-time installs (skills.sh)
  • +85 installs in the week ending Aug 5, 2026 (Skillselion tracking)
  • Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/affaan-m/ecc --skill csharp-testing

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs1.4k
repo stars238k
Last updatedAugust 5, 2026
Repositoryaffaan-m/ecc

How do you write xUnit tests for .NET services?

Generate high-quality, maintainable tests for C# and.NET services using xUnit, FluentAssertions, and modern mocking patterns.

Who is it for?

.NET developers writing or reviewing C# unit and integration tests who want agent guidance on xUnit, FluentAssertions, mocking, and ASP.NET Core test infrastructure.

Skip if: Teams working in Python, JavaScript, or Go codebases without C# or .NET test projects to maintain.

When should I use this skill?

The user mentions C# tests, xUnit, FluentAssertions, .NET integration tests, Testcontainers, WebApplicationFactory, or flaky .NET tests.

What you get

xUnit test suites, FluentAssertions specs, mock setups, integration tests, and .NET test project scaffolding.

  • xUnit test classes
  • integration test setup
  • mock configurations

By the numbers

  • Documents a 6-tool .NET testing stack: xUnit, FluentAssertions, NSubstitute/Moq, Testcontainers, WebApplicationFactory,

Files

SKILL.mdMarkdownGitHub ↗

C#テストパターン

xUnit、FluentAssertions、最新のテストプラクティスを使用した.NETアプリケーションの包括的なテストパターン。

起動条件

  • C#コードの新しいテストを書く場合
  • テスト品質とカバレッジのレビュー
  • .NETプロジェクトのテストインフラストラクチャの設定
  • フレーキーまたは遅いテストのデバッグ

テストフレームワークスタック

ツール目的
xUnitテストフレームワーク(.NETに推奨)
FluentAssertions読みやすいアサーション構文
NSubstituteまたはMoq依存関係のモッキング
Testcontainers統合テストでの実際のインフラ
WebApplicationFactoryASP.NET Core統合テスト
Bogus現実的なテストデータ生成

ユニットテスト構造

Arrange-Act-Assert

public sealed class OrderServiceTests
{
    private readonly IOrderRepository _repository = Substitute.For<IOrderRepository>();
    private readonly ILogger<OrderService> _logger = Substitute.For<ILogger<OrderService>>();
    private readonly OrderService _sut;

    public OrderServiceTests()
    {
        _sut = new OrderService(_repository, _logger);
    }

    [Fact]
    public async Task PlaceOrderAsync_ReturnsSuccess_WhenRequestIsValid()
    {
        // Arrange
        var request = new CreateOrderRequest
        {
            CustomerId = "cust-123",
            Items = [new OrderItem("SKU-001", 2, 29.99m)]
        };

        // Act
        var result = await _sut.PlaceOrderAsync(request, CancellationToken.None);

        // Assert
        result.IsSuccess.Should().BeTrue();
        result.Value.Should().NotBeNull();
        result.Value!.CustomerId.Should().Be("cust-123");
    }

    [Fact]
    public async Task PlaceOrderAsync_ReturnsFailure_WhenNoItems()
    {
        // Arrange
        var request = new CreateOrderRequest
        {
            CustomerId = "cust-123",
            Items = []
        };

        // Act
        var result = await _sut.PlaceOrderAsync(request, CancellationToken.None);

        // Assert
        result.IsSuccess.Should().BeFalse();
        result.Error.Should().Contain("at least one item");
    }
}

Theoryによるパラメータ化テスト

[Theory]
[InlineData("", false)]
[InlineData("a", false)]
[InlineData("ab@c.d", false)]
[InlineData("user@example.com", true)]
[InlineData("user+tag@example.co.uk", true)]
public void IsValidEmail_ReturnsExpected(string email, bool expected)
{
    EmailValidator.IsValid(email).Should().Be(expected);
}

[Theory]
[MemberData(nameof(InvalidOrderCases))]
public async Task PlaceOrderAsync_RejectsInvalidOrders(CreateOrderRequest request, string expectedError)
{
    var result = await _sut.PlaceOrderAsync(request, CancellationToken.None);

    result.IsSuccess.Should().BeFalse();
    result.Error.Should().Contain(expectedError);
}

public static TheoryData<CreateOrderRequest, string> InvalidOrderCases => new()
{
    { new() { CustomerId = "", Items = [ValidItem()] }, "CustomerId" },
    { new() { CustomerId = "c1", Items = [] }, "at least one item" },
    { new() { CustomerId = "c1", Items = [new("", 1, 10m)] }, "SKU" },
};

NSubstituteによるモッキング

[Fact]
public async Task GetOrderAsync_ReturnsNull_WhenNotFound()
{
    // Arrange
    var orderId = Guid.NewGuid();
    _repository.FindByIdAsync(orderId, Arg.Any<CancellationToken>())
        .Returns((Order?)null);

    // Act
    var result = await _sut.GetOrderAsync(orderId, CancellationToken.None);

    // Assert
    result.Should().BeNull();
}

[Fact]
public async Task PlaceOrderAsync_PersistsOrder()
{
    // Arrange
    var request = ValidOrderRequest();

    // Act
    await _sut.PlaceOrderAsync(request, CancellationToken.None);

    // Assert — リポジトリが呼び出されたことを検証
    await _repository.Received(1).AddAsync(
        Arg.Is<Order>(o => o.CustomerId == request.CustomerId),
        Arg.Any<CancellationToken>());
}

ASP.NET Core統合テスト

WebApplicationFactoryのセットアップ

public sealed class OrderApiTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly HttpClient _client;

    public OrderApiTests(WebApplicationFactory<Program> factory)
    {
        _client = factory.WithWebHostBuilder(builder =>
        {
            builder.ConfigureServices(services =>
            {
                // テスト用にインメモリDBで実際のDBを置き換え
                services.RemoveAll<DbContextOptions<AppDbContext>>();
                services.AddDbContext<AppDbContext>(options =>
                    options.UseInMemoryDatabase("TestDb"));
            });
        }).CreateClient();
    }

    [Fact]
    public async Task GetOrder_Returns404_WhenNotFound()
    {
        var response = await _client.GetAsync($"/api/orders/{Guid.NewGuid()}");

        response.StatusCode.Should().Be(HttpStatusCode.NotFound);
    }

    [Fact]
    public async Task CreateOrder_Returns201_WithValidRequest()
    {
        var request = new CreateOrderRequest
        {
            CustomerId = "cust-1",
            Items = [new("SKU-001", 1, 19.99m)]
        };

        var response = await _client.PostAsJsonAsync("/api/orders", request);

        response.StatusCode.Should().Be(HttpStatusCode.Created);
        response.Headers.Location.Should().NotBeNull();
    }
}

Testcontainersによるテスト

public sealed class PostgresOrderRepositoryTests : IAsyncLifetime
{
    private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder()
        .WithImage("postgres:16-alpine")
        .Build();

    private AppDbContext _db = null!;

    public async Task InitializeAsync()
    {
        await _postgres.StartAsync();
        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseNpgsql(_postgres.GetConnectionString())
            .Options;
        _db = new AppDbContext(options);
        await _db.Database.MigrateAsync();
    }

    public async Task DisposeAsync()
    {
        await _db.DisposeAsync();
        await _postgres.DisposeAsync();
    }

    [Fact]
    public async Task AddAsync_PersistsOrder()
    {
        var repo = new SqlOrderRepository(_db);
        var order = Order.Create("cust-1", [new OrderItem("SKU-001", 2, 10m)]);

        await repo.AddAsync(order, CancellationToken.None);

        var found = await repo.FindByIdAsync(order.Id, CancellationToken.None);
        found.Should().NotBeNull();
        found!.Items.Should().HaveCount(1);
    }
}

テスト組織

tests/
  MyApp.UnitTests/
    Services/
      OrderServiceTests.cs
      PaymentServiceTests.cs
    Validators/
      EmailValidatorTests.cs
  MyApp.IntegrationTests/
    Api/
      OrderApiTests.cs
    Repositories/
      OrderRepositoryTests.cs
  MyApp.TestHelpers/
    Builders/
      OrderBuilder.cs
    Fixtures/
      DatabaseFixture.cs

テストデータビルダー

public sealed class OrderBuilder
{
    private string _customerId = "cust-default";
    private readonly List<OrderItem> _items = [new("SKU-001", 1, 10m)];

    public OrderBuilder WithCustomer(string customerId)
    {
        _customerId = customerId;
        return this;
    }

    public OrderBuilder WithItem(string sku, int quantity, decimal price)
    {
        _items.Add(new OrderItem(sku, quantity, price));
        return this;
    }

    public Order Build() => Order.Create(_customerId, _items);
}

// テストでの使用
var order = new OrderBuilder()
    .WithCustomer("cust-vip")
    .WithItem("SKU-PREMIUM", 3, 99.99m)
    .Build();

よくあるアンチパターン

アンチパターン修正方法
実装の詳細をテストする動作と結果をテストする
共有の可変テスト状態テストごとに新しいインスタンス(xUnitはコンストラクタでこれを行う)
非同期テストでのThread.Sleepタイムアウトまたはポーリングヘルパーを使用したTask.Delay
ToString()出力のアサーション型付きプロパティのアサーション
テストごとに1つの巨大なアサーションテストごとに1つの論理的なアサーション
実装を記述するテスト名動作で命名: Method_ExpectedResult_WhenCondition
CancellationTokenを無視する常に渡してキャンセルを確認する

テストの実行

# すべてのテストを実行
dotnet test

# カバレッジを付けて実行
dotnet test --collect:"XPlat Code Coverage"

# 特定のプロジェクトを実行
dotnet test tests/MyApp.UnitTests/

# テスト名でフィルタリング
dotnet test --filter "FullyQualifiedName~OrderService"

# 開発中のウォッチモード
dotnet watch test --project tests/MyApp.UnitTests/

Related skills

How it compares

Choose csharp-testing over language-agnostic testing skills when the codebase is C# or .NET and xUnit with FluentAssertions is the target stack.

FAQ

Which test frameworks does csharp-testing use?

csharp-testing uses xUnit as the primary .NET test framework with FluentAssertions for readable assertions, plus NSubstitute or Moq for mocking, Testcontainers for infrastructure integration tests, and WebApplicationFactory for ASP.NET Core apps.

When should csharp-testing be invoked?

csharp-testing should be invoked when writing new C# tests, reviewing test quality and coverage, setting up .NET test infrastructure, or debugging flaky and slow tests in .NET service codebases.

Testing & QAbackendtesting

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.