How to get an instance of IConfiguration in asp.net core?
Asked Answered
Y

1

31

I making a unittesting project to test my webapi and i need to initialize a controller the problem is that in the constructor it receive a IConfiguration that it is provide by dependency-injection and works fine.

But when I want to initialize it manually i have not way to get this instance.

I am trying to initialize it from a unittest project no inside of the same project.

The controller looks like:

public Controller(IConfiguration configuration) { _configuration = configuration; }
Yalonda answered 29/12, 2017 at 4:26 Comment(0)
F
53

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();
Finitude answered 29/12, 2017 at 4:48 Comment(2)
What namespace is the ConfigurationBuilder from?Carolinecarolingian
Found it, it's Microsoft.Extensions.Configuration.JsonCarolinecarolingian

© 2022 - 2024 — McMap. All rights reserved.