Using ASP.NET Core's ConfigurationBuilder in a Test Project

You can use the ConfigurationBuilder in a test project with a couple of steps. I don't think you will need the IHostingEnvironment interface itself.

First, add two NuGet packages to your project which have the ConfigurationBuilder extension methods:

"dependencies": {
  "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc1-final",
  "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final"
}

Second, put your desired environment variables into the test project's properties:

environment variable dialog

Then you can create your own builder in the test project:

private readonly IConfigurationRoot _configuration;

public BuildConfig()
{
    var environmentName = Environment.GetEnvironmentVariable("Hosting:Environment");

    var config = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{environmentName}.json", true)
        .AddEnvironmentVariables();

    _configuration = config.Build();
}

If you want to use precisely the same settings file (not a copy), then you'll need to add in a path to it.


I'll add this answer here for completeness, as I experienced the same issue as @vaindil describes in Will's answer here. The reason was that we populated our IConfiguration from environment variables in the code under test. This overrode any config we set in test using say an appsettings.json. Our solution was to create environment variables for the test process using System.Environment.SetEnvironvironmentVariable("variableName", "variableValue")

Effectively, the instance of WebHostBuilder in our tests is created the same as our hosted API:

// Code omitted for brevity
var builder = new WebHostBuilder()                 
                .UseEnvironment("Development")
                .ConfigureAppConfiguration(configurationBuilder => configurationBuilder.AddEnvironmentVariables())
                .UseStartup<Startup>();

var testServer = new TestServer(builder); // test against this