Resolve IOptions<T> in Unit Test

2.4k Views Asked by At

I have a class such as this:

public class Test : ITest
{
    public Test(IOptions<CustomSection> settings)
    {
        //do something
    }
}

I would like to unit test and just maintain the dependency injection. So to accomplish this I have tried the following:

var builder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", true, true)
    .AddEnvironmentVariables();

var configurationRoot = builder.Build();

//This is a method that injects various services.
var services = InjectServices();

services.AddSingleton<IConfiguration>(configurationRoot);
var provider = services.BuildServiceProvider();

var my service = provider.GetService<ITest>();

However, I get the following error:

Unable to resolve servifor type 'Microsoft.Extensions.Options.IOptions`1[Test]' while attempting to activate 'Test'.

How can I add IOptions to injection? I thought that services.AddSingleton<IConfiguration>(configurationRoot); would do the trick, but it doesn't seem to. Also, my configuration is correct, if I use the same appsettings in my main project, there is no problems.

1

There are 1 best solutions below

4
On BEST ANSWER

You have forgotten to register services required for using options:

// extension method defined in Microsoft.Extensions.Options
services.AddOptions();

Also, you should setup how to build CustomSection from configurations by something like this:

services.Configure<CustomSection>(configurationRoot);

Reference Configuration in ASP.NET Core

Reference Options pattern in ASP.NET Core