ASP.NET Core Interview Question #204

How can dependencies be replaced in ASP.NET Core integration tests?

Testing, Deployment & Hosting Senior Advanced

Quick Interview Answer

Integration tests often need test-specific implementations for external systems or infrastructure. WebApplicationFactory can customize the application's service collection before the test host starts.

Detailed Explanation

Integration tests often need test-specific implementations for external systems or infrastructure. WebApplicationFactory can customize the application's service collection before the test host starts.

For example, a production repository can be removed and replaced with a fake, or a real external API client can be replaced with a deterministic test implementation.

The goal is to preserve the parts of the application being integrated while controlling dependencies that would make tests slow, destructive, expensive, or unreliable.

Code Example

var factory = new WebApplicationFactory<Program>()
    .WithWebHostBuilder(builder =>
    {
        builder.ConfigureServices(services =>
        {
            services.RemoveAll<IEmailSender>();
            services.AddSingleton<IEmailSender, FakeEmailSender>();
        });
    });

var client = factory.CreateClient();