Deserialize appsettings.json in unit test

Viewed 3295

There are many examples out there that show how to deserialize your app settings within the Startup.cs class. I get that. But that's not what I'm asking. I'm working within a unit test constructor.

This question is close: Read appsettings json values in .NET Core Test Project But in reading it carefully, I'm not seeing a slam dunk answer.

appsettings.json:

{
  "AppSettings": {
    "myKey1": "myValue1",
    "myKey2": "myValue2",
  }
}

And:

public class AppSettings
{
    public string myKey1 { get; set; }
    public string myKey2 { get; set; }
}

I am able to get single values just fine:

var config = new ConfigurationBuilder()
              .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
              .Build();
var myValue1 = config.GetSection("AppSettings:myKey1 ").Value;

But what I'm not figuring out is how to get create an instance of AppSettings. I've tried:

var appSettings = config.GetValue<AppSettings>("AppSettings");

But that ends up null. And I've played around with trying to create my own instance of IServiceCollection so I could do something like you might in Startup.cs, but I'm not making any progress.

4 Answers

I ended up just doing this.

public class AppSettings
{
    AppSettings(IConfigurationRoot config)
    {
            myKey1 = config.GetSection("AppSettings:MyKey1").Value;
            myKey2 = config.GetSection("AppSettings:MyKey2").Value;
    }

    public string myKey1 { get; set; }
    public string myKey2 { get; set; }
}

Not ideal but it gets the job done and I can move on.

I believe you would have to create a new instance of IConfiguration and then get its values like you already are doing.

public UnitTestConstructor(IConfiguration configuration){
      Configuration = configuration;
}

public IConfiguration Configuration { get; }

public TestOne(){
      var appSettingsValue = Configuration.GetValue<string>("AppSettings:MyValue");
}

You have to use the Microsoft.Extensions.Configuration.Binder extension, available as a separate package on NuGet.

Specifically, use the Configuration.Bind() method:

AppSettings appSettings;

config.Bind(appSettings);

Or even simpler:

var appSettings = config.Get<AppSettings>();

You could also bind it with help of DI:

services.Configure<AppSettings>(_configuration.GetSection("AppSettings"));

Then in your service that needs these settings, just add AppSettings appSettings as a dependency to it and the dependency should auto-resolve.

Related