ASP.NET Core Web API Interview Question #155

How can dependencies be replaced in integration tests?

Testing, HttpClient, Integration Testing, Background Services & Deployment Senior Advanced

Quick Interview Answer

WebApplicationFactory can customize the service collection for tests. A production dependency can be removed and replaced with a test implementation, mock, fake, or test database configuration.

Detailed Explanation

WebApplicationFactory can customize the service collection for tests. A production dependency can be removed and replaced with a test implementation, mock, fake, or test database configuration.

Only replace what the test intentionally controls. Excessive mocking in integration tests can reduce their ability to detect real integration failures.

Code Example

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