Csharp testing patterns

From FerroxLabs/murage · View interactive version

Csharp testing patterns is an AI agent skill from the GitHub repository FerroxLabs/murage. Guides expert-level C# testing: xUnit, Moq, FluentAssertions, WebApplicationFactory for integration testing, and test architecture patterns for .NET applications. Use when the user asks about C# testing, xUnit, Moq, FluentAssertions, WebApplicationFactory, .NET testing, integration testing. Do NOT u

How to use this skill

Skill file

C# Testing Patterns

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Assess the Testing Scope and Classify Test Types

Before writing a single line of test code, determine which layer of the test pyramid the work lives in.

2. Configure the xUnit Project Correctly

xUnit is the dominant choice for .NET because of its parallelism model, extensibility, and lack of test-class-level shared mutable state.

{
  "parallelizeAssembly": true,
  "parallelizeTestCollections": true,
  "maxParallelThreads": 4
}

3. Design the Test Class and Fixture Architecture

xUnit's lifecycle model differs from NUnit and MSTest. Understanding it prevents resource leaks and flaky tests.

public class OrderServiceFixture : IAsyncLifetime
{
    public AppDbContext DbContext { get; private set; } = null!;

    public async Task InitializeAsync()
    {
        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseInMemoryDatabase(Guid.NewGuid().ToString())
            .Options;
        DbContext = new AppDbContext(options);
        await DbContext.Database.EnsureCreatedAsync();
    }

    public async Task DisposeAsync() => await DbContext.DisposeAsync();
}

4. Write Unit Tests with Moq and FluentAssertions

Effective unit tests have three regions: Arrange, Act, Assert. Make these regions visible with blank lines or comments.

[Fact]
public async Task ProcessOrder_WhenStockIsInsufficient_ThrowsInsufficientStockException()
{
    // Arrange
    var inventoryService = new Mock<IInventoryService>();
    inventoryService
        .Setup(x => x.GetAvailableStockAsync(It.IsAny<Guid>()))
        .ReturnsAsync(0);

    var sut = new OrderService(inventoryService.Object);
    var order = OrderBuilder.Default().WithQuantity(5).Build();

    // Act
    Func<Task> act = () => sut.ProcessOrderAsync(order);

    // Assert
    await act.Should()
        .ThrowExactly<InsufficientStockException>()
        .WithMessage("*insufficient stock*");

    inventoryService.Verify(
        x => x.GetAvailableStockAsync(order.ProductId),
        Times.Once());
}

5. Use Theory Tests for Parameterized Cases

Avoid duplicating test logic by using [Theory] with data sources when the same behavior must be verified across multiple inputs.

[Theory]
[MemberData(nameof(InvalidOrderData))]
public void CreateOrder_WithInvalidInput_ThrowsValidationException(
    string productId, int quantity, string expectedMessage)
{
    var act = () => Order.Create(productId, quantity);

    act.Should()
        .ThrowExactly<ValidationException>()
        .WithMessage(expectedMessage);
}

public static TheoryData<string, int, string> InvalidOrderData => new()
{
    { "", 1, "*product ID*" },
    { "SKU-001", 0, "*quantity must be positive*" },
    { "SKU-001", -5, "*quantity must be positive*" },
    { "SKU-001", 10_001, "*exceeds maximum*" }
};

6. Write Integration Tests with WebApplicationFactory

WebApplicationFactory<TProgram> bootstraps the full ASP.NET Core host in-process, including the DI container, middleware pipeline, and routing. This makes it ideal for testing controller behavior, middleware effects, and end-to-end request/response contracts.

public class TestWebAppFactory : WebApplicationFactory<Program>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =>
        {
            // Replace real DbContext with SQLite in-memory
            var descriptor = services.SingleOrDefault(
                d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
            if (descriptor is not null) services.Remove(descriptor);

            services.AddDbContext<AppDbContext>(options =>
                options.UseSqlite("DataSource=:memory:"));

            // Replace real external HTTP client
            services.AddSingleton<IPaymentGateway, FakePaymentGateway>();
        });

        builder.UseEnvironment("Testing");
    }
}

7. Test EF Core Repositories and Data Access

EF Core provides specific test strategies. Choose based on what you need to validate.

8. Configure Coverage, Mutation Testing, and CI Gates

Coverage measurement is a safety net, not a goal. Use it to identify untested paths, not to chase 100%.

- name: Run Tests with Coverage
  run: dotnet test --configuration Release --collect:"XPlat Code Coverage" --results-directory ./coverage

- name: Check Coverage Threshold
  run: |
    dotnet reportgenerator \
      -reports:./coverage/**/coverage.cobertura.xml \
      -targetdir:./coverage/report \
      -reporttypes:Cobertura
    # Fail if branch coverage < 80%
    python scripts/check_coverage.py --threshold 80

Output Format

When helping a user implement or review C# testing patterns, produce output in this structure:

## Test Architecture Decision

**Test Type:** [Unit | Integration | Component]
**Subject Under Test:** [ClassName.MethodName or API endpoint]
**Dependencies Identified:** [list all injected dependencies]
**Mocking Strategy:** [Mock with Moq | Fake implementation | In-memory DB | WebApplicationFactory]

---

## Test Project Configuration

### Packages (add to .csproj)
| Package | Version | Purpose |
|---------|---------|---------|
| xunit | 2.9.x | Test runner and attributes |
| xunit.runner.visualstudio | 2.8.x | VS Test Explorer integration |
| Microsoft.NET.Test.Sdk | 17.x | dotnet test CLI support |
| FluentAssertions | 6.12.x | Readable assertion API |
| Moq | 4.20.x | Mock object framework |
| coverlet.collector | 6.x | Code coverage collection |
| Microsoft.AspNetCore.Mvc.Testing | 8.x | WebApplicationFactory (integration only) |

---

## Test Class Structure

// [naming: {ProjectName}.Tests/{Layer}/{ClassName}Tests.cs]

public class [ClassName]Tests : IClassFixture<[FixtureType]> // omit fixture if not needed

{

// Dependencies

private readonly Mock<[IDependency]> _mockDependency;

private readonly [ClassName] _sut; // "sut" = system under test

public [ClassName]Tests()

{

_mockDependency = new Mock<[IDependency]>();

_sut = new ClassName;

}

// Test methods follow naming: MethodName_State_ExpectedOutcome

[Fact]

public async Task MethodName_WhenCondition_ExpectedBehavior()

{

// Arrange

// Act

// Assert (FluentAssertions)

}

}


---

## Coverage Configuration (Directory.Build.props or .csproj)

<PropertyGroup>

<CollectCoverage>true</CollectCoverage>

<CoverletOutputFormat>cobertura</CoverletOutputFormat>

<Threshold>80</Threshold>

<ThresholdType>branch</ThresholdType>

<ExcludeByAttribute>ExcludeFromCodeCoverage,GeneratedCode</ExcludeByAttribute>

<Exclude>[.Migrations],[.Program]</Exclude>

</PropertyGroup>


Rules

  1. Never use [SetUp]/[TearDown] attribute patterns from NUnit in xUnit. xUnit has no [SetUp] attribute. Setup goes in the constructor; teardown goes in IDisposable.Dispose(). Mixing NUnit patterns in xUnit breaks the test lifecycle model.
  1. Never use Mock<T>() with MockBehavior.Loose when behavior verification matters. MockBehavior.Strict causes unset calls to throw immediately, surfacing unexpected interactions. Use Strict for service orchestrators where unexpected calls indicate a design problem, and Loose only for pure data-access mocks.
  1. Never share Mock<T> instances between tests via static fields. Each test must construct its own mocks. Shared mocks accumulate state across tests (setup calls stack, verification counters accumulate), causing false passes and order-dependent failures.
  1. Never use Thread.Sleep or Task.Delay as synchronization primitives. Async code must be tested with async Task test methods. Use await throughout. If testing time-dependent behavior, inject TimeProvider (from .NET 8) or IClock abstraction and control time in tests.
  1. Always use BeEquivalentTo with explicit exclusions for domain objects. Equals overrides on domain objects may not cover all comparison dimensions. BeEquivalentTo does deep structural comparison by default, which catches regressions in nested objects -- but always exclude auto-generated fields like Id, CreatedAt, and RowVersion.
  1. Never call mock.VerifyAll() as a substitute for explicit Verify() calls. VerifyAll() verifies all setups were called, but a setup that was never called without a corresponding Verify() fails silently when VerifyAll() is absent. Be explicit about what behavior you are verifying and why.
  1. Never use UseInMemoryDatabase for tests that verify constraint or transaction behavior. The EF Core in-memory provider does not enforce unique indexes, foreign key constraints, or database-level validation. Use UseSqlite("DataSource=:memory:") for constraint testing and TestContainers for full SQL Server/PostgreSQL dialect testing.
  1. Always create isolated database instances per test or per test class. Use Guid.NewGuid().ToString() as the database name when using in-memory providers. Sharing a database name across test classes causes data contamination, especially when EF Core's change tracker is involved.
  1. Never assert on log output as the primary verification mechanism. Log messages are implementation details and change frequently. Assert on return values, thrown exceptions, state changes, and explicit mock verifications. Log assertions are acceptable only for structured logging tests where the log event is the observable contract.
  1. Always configure xunit.runner.json to limit parallel threads explicitly. Unrestricted parallelism causes intermittent failures in integration tests that share infrastructure (ports, file handles, database names). Set maxParallelThreads to the number of available CPU cores or 4, whichever is lower. Separate integration tests into a [Collection] with a single shared fixture to serialize them.

Edge Cases

Legacy Codebase Without Dependency Injection

When the codebase uses new keywords to instantiate dependencies inside methods (static dependencies, service locators, HttpClient constructed inline), direct mocking is not possible.

Testing Authenticated Endpoints with WebApplicationFactory

The real authentication stack requires valid JWT tokens or cookies. In test environments, this creates a circular dependency.

Testing Code That Uses `DateTime.UtcNow` Directly

Code that calls DateTime.UtcNow or DateTimeOffset.UtcNow directly is non-deterministic and non-testable for time-sensitive logic.

EF Core Repository Tests with Slow TestContainers Startup

Spinning up a PostgreSQL or SQL Server container takes 3--10 seconds per test session. Without proper sharing, this makes integration test suites prohibitively slow.

Testing MediatR Handlers, CQRS Commands, and Queries

In CQRS architectures using MediatR, there is a temptation to test handlers through the IMediator.Send() interface. This couples tests to the mediator pipeline unnecessarily for pure business logic.

Flaky Integration Tests Due to Port Conflicts

When multiple test projects run in parallel in CI and each creates a WebApplicationFactory, Kestrel may attempt to bind to the same port.

Testing Internal Classes

Production code often uses internal visibility for domain logic that should not be in the public API.


Example

Input: "I'm building an e-commerce order processing service. I have an OrderService that depends on IInventoryService and IPaymentGateway. I need unit tests for the PlaceOrderAsync method which checks stock, charges the customer, and creates an order record. How should I set this up with xUnit, Moq, and FluentAssertions?"

Output:

Test Architecture Decision

Test Type: Unit

Subject Under Test: OrderService.PlaceOrderAsync

Dependencies Identified: IInventoryService, IPaymentGateway, IOrderRepository

Mocking Strategy: Mock all three interfaces with Moq; use MockBehavior.Strict for IPaymentGateway to catch unexpected charge attempts


Packages (add to `OrderService.Tests.csproj`)

| Package | Version | Purpose |

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

| xunit | 2.9.x | Test runner |

| xunit.runner.visualstudio | 2.8.x | VS Test Explorer |

| Microsoft.NET.Test.Sdk | 17.x | dotnet test support |

| FluentAssertions | 6.12.x | Assertion API |

| Moq | 4.20.x | Mock objects |

| coverlet.collector | 6.x | Coverage collection |


Full Test Implementation

// File: OrderService.Tests/Unit/OrderServiceTests.cs

using FluentAssertions;
using Moq;
using Xunit;
using ECommerce.Orders;
using ECommerce.Inventory;
using ECommerce.Payments;

namespace ECommerce.Tests.Unit;

public class OrderServiceTests
{
    private readonly Mock<IInventoryService> _inventoryService;
    private readonly Mock<IPaymentGateway> _paymentGateway;
    private readonly Mock<IOrderRepository> _orderRepository;
    private readonly OrderService _sut;

    public OrderServiceTests()
    {
        // Use Strict to catch any unexpected payment calls
        _paymentGateway = new Mock<IPaymentGateway>(MockBehavior.Strict);
        _inventoryService = new Mock<IInventoryService>();
        _orderRepository = new Mock<IOrderRepository>();

        _sut = new OrderService(
            _inventoryService.Object,
            _paymentGateway.Object,
            _orderRepository.Object);
    }

    // -------------------------------------------------------
    // Happy path
    // -------------------------------------------------------

    [Fact]
    public async Task PlaceOrderAsync_WhenStockAvailableAndPaymentSucceeds_ReturnsConfirmedOrder()
    {
        // Arrange
        var customerId = Guid.NewGuid();
        var productId = Guid.NewGuid();
        var request = new PlaceOrderRequest(customerId, productId, Quantity: 2, UnitPrice: 49.99m);

        _inventoryService
            .Setup(x => x.GetAvailableStockAsync(productId))
            .ReturnsAsync(10);

        _paymentGateway
            .Setup(x => x.ChargeAsync(customerId, 99.98m, It.IsAny<CancellationToken>()))
            .ReturnsAsync(new PaymentResult(Success: true, TransactionId: "TXN-001"));

        _orderRepository
            .Setup(x => x.SaveAsync(It.IsAny<Order>(), It.IsAny<CancellationToken>()))
            .Returns(Task.CompletedTask);

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

        // Assert
        result.Should().NotBeNull();
        result.Status.Should().Be(OrderStatus.Confirmed);
        result.TransactionId.Should().Be("TXN-001");
        result.TotalAmount.Should().Be(99.98m);

        _orderRepository.Verify(
            x => x.SaveAsync(
                It.Is<Order>(o =>
                    o.CustomerId == customerId &&
                    o.ProductId == productId &&
                    o.Status == OrderStatus.Confirmed),
                It.IsAny<CancellationToken>()),
            Times.Once());
    }

    // -------------------------------------------------------
    // Stock insufficient -- no payment should be attempted
    // -------------------------------------------------------

    [Fact]
    public async Task PlaceOrderAsync_WhenStockInsufficient_ThrowsInsufficientStockException()
    {
        // Arrange
        var productId = Guid.NewGuid();
        var request = new PlaceOrderRequest(Guid.NewGuid(), productId, Quantity: 5, UnitPrice: 20m);

        _inventoryService
            .Setup(x => x.GetAvailableStockAsync(productId))
            .ReturnsAsync(3); // Only 3 available, 5 requested

        // Act
        Func<Task> act = () => _sut.PlaceOrderAsync(request, CancellationToken.None);

        // Assert
        await act.Should()
            .ThrowExactly<InsufficientStockException>()
            .WithMessage("*insufficient stock*");

        // Strict MockBehavior ensures _paymentGateway was never called.
        // If ChargeAsync is called, the strict mock throws automatically.
        _orderRepository.Verify(
            x => x.SaveAsync(It.IsAny<Order>(), It.IsAny<CancellationToken>()),
            Times.Never());
    }

    // -------------------------------------------------------
    // Payment failure -- order must be marked failed, not saved as confirmed
    // -------------------------------------------------------

    [Fact]
    public async Task PlaceOrderAsync_WhenPaymentFails_ThrowsPaymentFailedException()
    {
        // Arrange
        var customerId = Guid.NewGuid();
        var productId = Guid.NewGuid();
        var request = new PlaceOrderRequest(customerId, productId, Quantity: 1, UnitPrice: 100m);

        _inventoryService
            .Setup(x => x.GetAvailableStockAsync(productId))
            .ReturnsAsync(50);

        _paymentGateway
            .Setup(x => x.ChargeAsync(customerId, 100m, It.IsAny<CancellationToken>()))
            .ReturnsAsync(new PaymentResult(Success: false, TransactionId: null));

        // Act
        Func<Task> act = () => _sut.PlaceOrderAsync(request, CancellationToken.None);

        // Assert
        await act.Should()
            .ThrowExactly<PaymentFailedException>()
            .WithMessage("*payment declined*");

        _orderRepository.Verify(
            x => x.SaveAsync(
                It.Is<Order>(o => o.Status == OrderStatus.Confirmed),
                It.IsAny<CancellationToken>()),
            Times.Never());
    }

    // -------------------------------------------------------
    // Parameterized: quantity edge cases
    // -------------------------------------------------------

    [Theory]
    [MemberData(nameof(InvalidQuantityData))]
    public async Task PlaceOrderAsync_WithInvalidQuantity_ThrowsValidationException(
        int quantity, string expectedMessageFragment)
    {
        // Arrange
        var request = new PlaceOrderRequest(Guid.NewGuid(), Guid.NewGuid(), quantity, 10m);

        // Act
        Func<Task> act = () => _sut.PlaceOrderAsync(request, CancellationToken.None);

        // Assert -- validation should fire before any dependency is touched
        await act.Should()
            .ThrowExactly<ValidationException>()
            .WithMessage(expectedMessageFragment);

        _inventoryService.Verify(
            x => x.GetAvailableStockAsync(It.IsAny<Guid>()),
            Times.Never());
    }

    public static TheoryData<int, string> InvalidQuantityData => new()
    {
        { 0,      "*quantity must be greater than zero*" },
        { -1,     "*quantity must be greater than zero*" },
        { 10_001, "*exceeds maximum order quantity*" }
    };
}

Coverage Configuration (`OrderService.Tests.csproj` fragment)

<PropertyGroup>
  <TargetFramework>net8.0</TargetFramework>
  <IsPackable>false</IsPackable>
  <Nullable>enable</Nullable>
  <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
  <PackageReference Include="xunit" Version="2.9.*" />
  <PackageReference Include="xunit.runner.visualstudio" Version="2.8.*" />
  <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.*" />
  <PackageReference Include="FluentAssertions" Version="6.12.*" />
  <PackageReference Include="Moq" Version="4.20.*" />
  <PackageReference Include="coverlet.collector" Version="6.*">
    <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    <PrivateAssets>all</PrivateAssets>
  </PackageReference>
</ItemGroup>

CI Command to Run and Gate Coverage

dotnet test OrderService.Tests \
  --configuration Release \
  --collect:"XPlat Code Coverage" \
  --results-directory ./TestResults \
  -- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Threshold=80 \
     DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.ThresholdType=branch

What this test suite achieves:

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.