loading experience

Architecture & quality

Testing in .NET with xUnit v3: unit and integration tests

How to organise the tests of a modern .NET project, from unit tests to APIs tested in memory.

Testing in .NET with xUnit v3: unit and integration tests

Tests are the safety net that lets you upgrade frameworks and libraries without fear. xUnit v3 is the new generation of one of the most widely used test frameworks in .NET.

The lower you go, the more numerous, fast and cheap the tests are.
The lower you go, the more numerous, fast and cheap the tests are.

A unit test

public class DiscountTests
{
    [Theory]
    [InlineData(100, 0)]
    [InlineData(200, 10)]
    [InlineData(1000, 100)]
    public void Compute_ReturnsExpectedDiscount(decimal total, decimal expected)
    {
        var discount = DiscountCalculator.For(total);
        Assert.Equal(expected, discount);
    }
}

What is new in xUnit v3

  • Test projects are executables and run on Microsoft's new, lighter testing platform.
  • TestContext.Current gives access to the running test, including a CancellationToken that is cancelled if the test is stopped.
  • Dynamically skipped tests and better support for asynchronous tests.

Integration tests for APIs

WebApplicationFactory starts the whole ASP.NET Core application in memory: requests go through real middleware, routing and serialisation, without opening network ports.

public class ProductsApiTests(WebApplicationFactory<Program> factory)
    : IClassFixture<WebApplicationFactory<Program>>
{
    [Fact]
    public async Task GetProducts_ReturnsOk()
    {
        var client = factory.CreateClient();
        var response = await client.GetAsync("/api/products", TestContext.Current.CancellationToken);
        response.EnsureSuccessStatusCode();
    }
}

What to test

Business rules with many fast unit tests; the main API paths with integration tests; a few end-to-end tests for critical flows. A test that fails randomly must be fixed immediately: otherwise nobody will trust the suite any more.

Comments (0)

No comments yet.

Leave a comment