Read appsettings json values in .NET Core Test Project

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")
                     .AddEnvironmentVariables() 
                     .Build();
                     return config;
             }
    

AddEnvironmentVariables (suggested in @RickStrahl blog ) is useful if you want to pass some secrets, that you prefer not store in appsettings.test.json

  1. 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>();

Leave a Comment