Course contentsShow
← C#
Lesson 1664 of 1,90815. Software Quality and TestingFree lesson

Measuring Integration Test Performance

Analyze and optimize the startup time of heavy integration test suites.

In this lesson, you will learn how to identify and prune the "startup tax" that slows down your integration test suites when using WebApplicationFactory.

As your suite grows, the overhead of spinning up the .NET Dependency Injection (DI) container, initializing Testcontainers, and running EF Core migrations for every single test class becomes a bottleneck. To optimize, you must first measure where the time is going.

Profiling the Startup

The most common performance killer is the re-initialization of your WebApplicationFactory. If every test class inherits from a base class that new-ups the factory, you are likely triggering a full application rebuild and DI container build for every file.

You can measure this by adding a simple diagnostic timer in your WebApplicationFactory override:

public class CustomWebApplicationFactory : WebApplicationFactory<Program>
{
    public CustomWebApplicationFactory()
    {
        var sw = Stopwatch.StartNew();
        // Container setup logic
        sw.Stop();
        Console.WriteLine($"Test Startup Latency: {sw.ElapsedMilliseconds}ms");
    }
}

Strategies for Optimization

Once you identify a high startup latency, use these techniques to trim the time:

  1. Shared Fixtures: Use IClassFixture or ICollectionFixture in xUnit to share a single factory instance across multiple test classes. This ensures the DI container is built exactly once per test run rather than once per class.
  2. Lazy Registration: Avoid resolving heavy services in the ConfigureTestServices override unless specifically required for the test. If a service is expensive to instantiate, consider using Lazy<T> to delay its creation until the first test actually hits that endpoint.
  3. Database Seeding Optimization: Instead of running full migrations via DbContext.Database.Migrate(), use a shared database snapshot or a Respawn checkpoint strategy. Migrating the schema is often the single most expensive operation in an integration test cycle.

By moving from "Per-Test Startup" to "Per-Suite Startup," you can often reduce a 10-minute test suite execution down to under a minute, significantly improving your feedback loop.

Key Takeaway: To optimize integration tests, measure the DI container and database initialization time, then leverage xUnit Class Fixtures to share these expensive resources across your test suite.