Problem
We use IConfiguration interface to get access for information of sections and connection strings from our appsettings.json. However, we also need to test our code by mocking this interface with our configurations.
Solution
Let’s look through example we have such appsetting.json
{
"ConnectionStrings": {
"default": "value",
"key1": "value"
},
"section1": {
"key0": "value",
"key1": "value"
}
}
Firstly we need only connection string to test our method. ConnectionStrings is a section, so let’s start from mocking section
var mockConfSection = new Mock<IConfigurationSection>();
mockConfSection.SetupGet(m => m[It.Is<string>(s => s == "default")]).Returns("mock value");
Now we can return our mocked section from GetSection method of IConfiguration interface.
var mockConfiguration = new Mock<IConfiguration>();
mockConfiguration.Setup(a => a.GetSection(It.Is<string>(s=>s == "ConnectionStrings"))).Returns(_mockConfSection.Object);
Briefly research gave me that answer. Even so , if we dive deeper, we may see that GetConnectionString extension method looks like
public static string GetConnectionString(this IConfiguration configuration, string name)
{
return configuration?.GetSection("ConnectionStrings")?[name];
}
It means that this method uses literal and after use name of subsection, but if we look to the documentation , we see that our full key is "ConnectionStrings:default"
As the result of all above we may optimize our test code
_configuration = new Mock<IConfiguration>();
_configuration.SetupGet(x => x[It.Is<string>(s=>s == "ConnectionStrings:default")]).Returns("mock value");
That’s enough.
