C# / .NET Compendium PLEN
.NET / C# / Testing

xUnit - the basics of testing in .NET

The structure of a basic test

public class OrderValidatorTests
{
    [Fact] // a test without parameters, checks ONE specific scenario
    public void Validate_EmptyOrder_ReturnsFalse()
    {
        // Arrange
        var validator = new OrderValidator();
        var order = new Order { Items = new List<OrderItem>() };

        // Act
        var result = validator.Validate(order);

        // Assert
        Assert.False(result);
    }
}

The AAA convention (Arrange-Act-Assert) - three sections: preparing the data, performing the action, checking the result. This is the standard in unit tests, making them readable - looking at a test you immediately see what is preparation and what is verification.

[Theory] - one test, many data sets

[Theory]
[InlineData(0, false)]
[InlineData(-5, false)]
[InlineData(100, true)]
public void Validate_TotalAmount_ReturnsExpectedResult(decimal amount, bool expected)
{
    var validator = new OrderValidator();
    var order = new Order { TotalAmount = amount };

    var result = validator.Validate(order);

    Assert.Equal(expected, result);
}

[Theory] + [InlineData] lets you avoid duplication - one test runs many times with different data sets, instead of writing 3 separate [Fact] methods that differ only in values.

[MemberData] - for more complex test data that can't be represented as literals in an attribute:

public static IEnumerable<object[]> OrderTestCases()
{
    yield return new object[] { new Order { Items = new List<OrderItem>() }, false };
    yield return new object[] { new Order { Items = new List<OrderItem> { new() } }, true };
}

[Theory]
[MemberData(nameof(OrderTestCases))]
public void Validate_VariousOrders_ReturnsExpectedResult(Order order, bool expected)
{
    var result = new OrderValidator().Validate(order);
    Assert.Equal(expected, result);
}

IClassFixture<T> - a shared context for many tests in a class

This solves the problem when preparing the test data is expensive (e.g. creating a connection to a test database) and you don't want to repeat it before every test:

public class DatabaseFixture : IDisposable
{
    public AppDbContext Context { get; }

    public DatabaseFixture()
    {
        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseInMemoryDatabase("TestDb") // an in-memory database, no real SQL Server
            .Options;

        Context = new AppDbContext(options);
        Context.Orders.Add(new Order { Id = 1, CustomerName = "Test" });
        Context.SaveChanges();
    }

    public void Dispose() => Context.Dispose();
}

public class OrderServiceTests : IClassFixture<DatabaseFixture>
{
    private readonly DatabaseFixture _fixture;

    public OrderServiceTests(DatabaseFixture fixture) // xUnit WSTRZYKUJE fixture do konstruktora
    {
        _fixture = fixture;
    }

    [Fact]
    public async Task GetOrder_ExistingId_ReturnsOrder()
    {
        var service = new OrderService(_fixture.Context);
        var order = await service.GetOrderAsync(1);
        Assert.NotNull(order);
    }
}

The key feature of IClassFixture: the fixture is created once for all the tests in a given class (not separately before each test) - the DatabaseFixture constructor runs once, and Dispose() is called after all the tests in the class finish.

Contrast with the test class constructor - xUnit creates a new instance of the test class for EACH test (so the tests are isolated), but IClassFixture breaks this, giving one shared fixture instance across all the tests of that class.

ICollectionFixture<T> - sharing across many test classes

[CollectionDefinition("Database collection")]
public class DatabaseCollection : ICollectionFixture<DatabaseFixture> { }

[Collection("Database collection")]
public class OrderServiceTests
{
    public OrderServiceTests(DatabaseFixture fixture) { }
}

[Collection("Database collection")] // THE SAME fixture, shared with OrderServiceTests
public class CustomerServiceTests
{
    public CustomerServiceTests(DatabaseFixture fixture) { }
}

Summary of the key attributes

Attribute/Interface Purpose
[Fact] A test of a single, specific scenario
[Theory] + [InlineData] A test with multiple, simple data sets
[Theory] + [MemberData] A test with more complex test data
IClassFixture<T> A shared context for all the tests in ONE class
ICollectionFixture<T> A shared context across MANY test classes
Buy me a coffee