Mocking .Net Core IConfiguration

The appsettings.json configuration can be mocked in several ways, the examples below use Moq.

Consider these settings:

1
2
3
4
5
6
7
{
"Services": {
"SomeService": {
"Url": "http://someservice:81"
}
}
}

This would be read in the consumer class as:

1
var url = config.GetValue<string>("Services:SomeService:Url");

Option 1: Mock configurationSection and configuration

In the testing class you need to mock configurationSection and configuration as follows

1
2
3
4
5
6
7
8
9
10
var configurationSectionMock = new Mock<IConfigurationSection>();
var configurationMock = new Mock<IConfiguration>();

configurationSectionMock
.Setup(x => x.Value)
.Returns("http://someservice:81");

configurationMock
.Setup(x => x.GetSection("Services:SomeService:Url"))
.Returns(configurationSectionMock.Object);

Then inject configurationMock.Object and it will be happy as when config.GetValue is called.

Option 2: Read appsettings file based on Environment

Build up configuration and read appsettings file.

1
2
3
4
5
6
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.{environment}.json")
.Build();

You can now read the configuration from configuration

1
2
var url = configuration.GetValue<string>("Services:SomeService:Url");
var connectionString = configuration.GetConnectionString("FooConnectionString");

Option 3: In Memory Collection

If the settings are nested and you need to mock several you can use a dictionary and add to the builder with .AddInMemoryCollection(appSettingsStub)

Consider these settings, the mock concearned with the RetryCount and RetrySleepDuration

1
2
3
4
5
6
7
8
9
{
"Services": {
"SomeService": {
"Url": "http://someservice:81",
"RetryCount": 3,
"RetrySleepDuration": 2
}
}
}

Create the dictionary

1
2
3
4
var appSettingsStub = new Dictionary<string, string> {
{"Services:SomeService:RetryCount", "3"},
{"Services:SomeService:RetrySleepDuration", "2"}
};

Create the config

1
2
3
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(appSettingsStub)
.Build();

Using a simple options class

1
2
3
4
5
6
7
public class SomeServiceOptions
{
public const string SomeService = "Services:SomeService";
public string Url { get; set; }
public int RetryCount { get; set; }
public int RetrySleepDuration { get; set; }
}

You can then access this config and bind it to the options class.

1
2
3
var someServiceConfig = configuration
.GetSection(SomeServiceOptions.SomeService)
.Get<SomeServiceOptions>();