I'd probably should start from the statement that in .Net Core application you should not pass instance of IConfiguration
to your controllers or other classes. You should use strongly typed settings injected through IOptions<T>
. See this article for more details: Options pattern in ASP.NET Core.
When using options pattern, you will have POCO for the settings required by a controller. This settings object is then injected into controller wrapped into IOptions<T>
:
public class ControllerSettings
{
public string Setting1 { get; set; }
public int Setting2 { get; set; }
// ...
}
public class Controller
{
private readonly ControllerSettings _settings;
public Controller(IOptions<ControllerSettings> options)
{
_settings = options.Value;
}
}
Then it's pretty simple to pass any settings you want from a Unit Test. Just fill settings instance and wrap to IOptions<T>
with any of available mocking frameworks, like Moq or NSubstitute:
[TestMethod]
public void SomeTest()
{
var settings = new ControllerSettings
{
Setting1 = "Some Value",
Setting2 = 123,
};
var options = new Mock<IOptions<ControllerSettings>>();
options.Setup(x => x.Value).Returns(settings);
var controller = new Controller(options.Object);
// ...
}
Sometimes it's required to use real configuration of the project, for example when developing integration test. In this case you could create instance of ConfigurationBuilder
and fill it with the same configuration sources as in tested code:
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
// Duplicate here any configuration sources you use.
configurationBuilder.AddJsonFile("AppSettings.json");
IConfiguration configuration = configurationBuilder.Build();