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

Add the configuration file

First, add a appconfig.json file to the Integration test project

Configure the appconfig.json file to be copied to the output directory by updating

enter image description here

Add NuGet package

  • Microsoft.Extensions.Configuration.Json

Use the configuration in your unit tests

[TestClass]
public class IntegrationTests
{
    public IntegrationTests()
    {
        var config = new ConfigurationBuilder().AddJsonFile("appconfig.json").Build();
        
        _numberOfPumps = Convert.ToInt32(config["NumberOfPumps"]);

        _numberOfMessages = Convert.ToInt32(config["NumberOfMessages"]);

        _databaseUrl = config["DatabaseUrlAddress"];
    }
} 

Suderson's solution worked for me when modified as below:

var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddEnvironmentVariables();

    IConfiguration config = builder.Build();

    //Now, You can use config.GetSection(key) to get the config entries