Search code examples
c#asp.net-coreasp.net-web-apiintegration-testing

How to use settings from integration testing project in the Startup class of api project?


I'm trying to write integration tests for web api, I have two appsettings.json files one for api project and other for integration tests. I want to use the values(azure storage connection strings) from integration testing project in Startup class of web api.

I have tried creating CustomWebApplicatonFactory it didn't work since the Startup class of web api gets settings like shown below.

//Configure services method in Startup class
public virtual void ConfigureServices(IServiceCollection services)
{
      var settings = ConfigurationProvider.GetConfiguration();
      services.TryAddSingleton(settings);
      services.AddHttpClient();
      var azureTableStorageConnectionString = 
      settings["AzureMainStoreConnectionStringSecretName"];

     //Other Startup related code
}

I want to change the value of "azureTableStorageConnectionString" from my integration test project. Help and suggestions are much appreciated.


Solution

  • First of all, instead of using the static function ConfigurationProvider.GetConfiguration() inject IConfiguration into your Startup class. The host that is usually defined in the Program class builds that for you so you can inject it.

    Then instead of using WebApplicationFactory<TStartup> you can build a test-host yourself like this.

    [Fact]
    public async Task LoadWeatherForecastAsync()
    {
        var webHostBuilder = new WebHostBuilder()
            .UseContentRoot(AppContext.BaseDirectory)
            .ConfigureAppConfiguration(builder =>
            {
                builder.Sources.Clear();
                builder.SetBasePath(AppContext.BaseDirectory);
                // this is an appsettings file located in the test-project!
                builder.AddJsonFile("appsettings.Testing.json", false);
            })
            .UseStartup<Startup>();
    
        var host = new TestServer(webHostBuilder);
    
        var response = await host.CreateClient().GetAsync("weatherforecast");
    
        Assert.True(response.IsSuccessStatusCode);
    }
    

    I've created a sample on github. You can clone it and try it out.