Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 357
Neville Nazerane Avatar asked Oct 17 '25 08:10

Neville Nazerane


1 Answers

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.

like image 136
Parth Sekar Avatar answered Oct 19 '25 13:10

Parth Sekar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!