Read appsettings json values in .NET Core Test Project

S.Siva picture S.Siva · Sep 30, 2016 · Viewed 70.1k times · Source

My Web application needs to read the Document DB keys from appsettings.json file. I have created a class with the key names and reading the Config section in ConfigureaServices() as:

public Startup(IHostingEnvironment env) {
    var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables();

    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

public void ConfigureServices(IServiceCollection services) {
    services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
    services.AddSession();
    Helpers.GetConfigurationSettings(services, Configuration);
    DIBuilder.AddDependency(services, Configuration);
}

I'm looking for the ways to read the Key values in Test project.

Answer

Michael Freidgeim picture Michael Freidgeim · Dec 1, 2017

This is based on the blog post Using Configuration files in .NET Core Unit Test Projects (written for .NET Core 1.0).

  1. Create (or copy) the appsettings.test.json in the Integration test project root directory, and in properties specify "Build Action" as Content and "Copy if newer" to Output Directory. Note that it’s better to have file name (e.g. appsettings.test.json ) different from normal appsettings.json, because it is possible that a file from the main project override the file from the test project, if the same name will be used.

  2. Include the JSON Configuration file NuGet package (Microsoft.Extensions.Configuration.Json) if it's not included yet.

  3. In the test project create a method,

    public static IConfiguration InitConfiguration()
            {
                var config = new ConfigurationBuilder()
                    .AddJsonFile("appsettings.test.json")
                    .Build();
                    return config;
            }
    
  4. Use the configuration as usual

    var config = InitConfiguration();
    var clientId = config["CLIENT_ID"]
    

BTW: You also may be interesting in reading the configuration into the IOptions class as described in Integration test with IOptions<> in .NET Core:

var options = config.Get<MySettings>();