Search code examples
dependency-injectionintegration-testing.net-6.0configurationmanager

remove configuration providers for integration tests in .NET 6


I currently have a web app on .NET 6 with integration tests using WebApplicationFactory. Here is a simplified version of my Program.cs file:

var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
var configuration = builder.Configuration;

services.AddAuthentication()
        .AddJwtBearer(o =>
        {
            var configs = configuration.GetRequiredSection("authOptions");
            // using configs here
        });
    

For most services I need to mock, I can remove them from the service descriptor. However, this would not work for services like adding authentication from what I have seen. Basically, I am looking for a way to mock the configurations for integration testing. The AddJwtBearer also has no access to the IServiceProvider and thus cannot use the injectable IConfiguration. I would like to account for all such features that need to use the configuration from builder.Configuration.

I am trying something like this:

public class CustomWebApplicationFactory: WebApplicationFactory<Program>
{

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {

        builder.ConfigureAppConfiguration(configBuilder =>
        {
             // remove all configs or at least user secrets from config builder
             // add mocked configurations
        });
    }

}
    

I would like to remove the configuration so as to make sure in future if I add a configuration I forget to mock, the integration test would throw an exception instead of using the user secrets.


Solution

  • I suggest the following approach if you would like to clear any existing default configuration providers and then add your custom configuration.

    public class CustomWebApplicationFactory: WebApplicationFactory<Program>
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
    
            builder.ConfigureAppConfiguration(configBuilder =>
            {
                //clears all the default configuration providers
                configBuilder.Sources.Clear();
                //Add your custom configuration from Json file or memory
            });
        }
    }
    

    You can find more examples here.

    Hope this helps.