Testing .NET 6 Applications: Integration Testing with WebApplicationFactory

Integration testing is the highest value testing you can do. In .NET 6, `WebApplicationFactory` makes it incredibly easy to spin up an in-memory version of your API for testing.

Exposing the Program Class

With Top-level statements, `Program` is internal. To test it, you need to expose it in `Program.cs`:

// Bottom of Program.cs
public partial class Program { }

The Test Setup

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

    public UserApiTests(WebApplicationFactory<Program> factory)
    {
        _client = factory
            .WithWebHostBuilder(builder =>
            {
                builder.ConfigureServices(services =>
                {
                    // Swap DB for In-Memory for testing
                    var descriptor = services.Single(d => d.ServiceType == typeof(DbContextOptions<MyDb>));
                    services.Remove(descriptor);
                    services.AddDbContext<MyDb>(options => options.UseInMemoryDatabase("TestDb"));
                });
            })
            .CreateClient();
    }

    [Fact]
    public async Task GetConsumers_ReturnsOk()
    {
        var response = await _client.GetAsync("/api/consumers");
        response.EnsureSuccessStatusCode();
    }
}

Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.