0

Thanks to this answer: Integration test and hosting ASP.NET Core 6.0 without Startup class

I have been able to perform integration tests with API.

WebApplicationFactory<Program>? app = new WebApplicationFactory<Program>()
    .WithWebHostBuilder(builder =>
    {
        builder.ConfigureServices(services =>
        {

        });
    });

HttpClient? client = app.CreateClient();

This has worked using the appsettings.json from the API project. Am now trying to use integrationtestsettings.json instead using:

IConfiguration configuration = new ConfigurationBuilder()
    .SetBasePath(ProjectDirectoryLocator.GetProjectDirectory())
    .AddJsonFile("integrationtestsettings.json")
    .Build();

WebApplicationFactory<Program>? app = new WebApplicationFactory<Program>()
    .WithWebHostBuilder(builder =>
    {
        builder.ConfigureAppConfiguration(cfg => cfg.AddConfiguration(configuration));
        
        builder.ConfigureServices(services =>
        {

        });
    });

_httpClient = app.CreateClient();

I have inspected the configuration variable and can see the properties loaded from my integrartiontestsettings.json file. However, the host is still running using the appsettings.json from the server project.

Previously, in .Net5, I was using WebHostBuilder and the settings were overridden by test settings.

    WebHostBuilder webHostBuilder = new();
    webHostBuilder.UseStartup<Startup>();
    webHostBuilder.ConfigureAppConfiguration(cfg => cfg.AddConfiguration(_configuration));

But cannot get the test settings to apply using the WebApplicationFactory.

Neil W
  • 7,670
  • 3
  • 28
  • 41

2 Answers2

1

It seems the method has changed.

Changing:

builder.ConfigureAppConfiguration(cfg => cfg.AddConfiguration(configuration));

To:

builder.UseConfiguraton(configuration);

has done the trick.

Neil W
  • 7,670
  • 3
  • 28
  • 41
0

builder.ConfigureAppConfiguration, now it's configuring the app (after your WebApplicationBuilder.Build() is called) and your WebApplication is created.

You need to "inject" your configurations before the .Build() is done. This is why you need to call UseConfiguraton instead of ConfigureAppConfiguration.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Cosmin
  • 21
  • 4