在单元测试中解析 IOptions<T>

Resolve IOptions<T> in Unit Test

我有一个 class 这样的:

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

我想进行单元测试并只维护依赖注入。所以为了做到这一点,我尝试了以下方法:

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>();

但是,我收到以下错误:

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

如何将 IOptions 添加到注入中?我认为 services.AddSingleton<IConfiguration>(configurationRoot); 可以解决问题,但似乎没有。另外,我的配置是正确的,如果我在我的主项目中使用相同的appsettings,就没有问题。

您忘记注册使用选项所需的服务:

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

此外,您应该设置如何通过这样的配置从配置构建 CustomSection

services.Configure<CustomSection>(configurationRoot);

引用Configuration in ASP.NET Core

引用Options pattern in ASP.NET Core