如何构建 IOptions<T> 进行测试?

How to build IOptions<T> for testing?

在 ASP.NET 核心 2 中,我有以下 class 需要 IOptions<T>

public class MyOptions
{
    public string Option1 { get; set; }
    public string Option2 { get; set; }
}


public class MyService:IMyService
{
  private readonly MyOptions _options;
  public MyService(IOptions<MyOptions> options)
  {
    _options = options.Value;
  }
}

appsettings.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },  
  "MyOptions": {
    "Option1": "option 1 value",
    "Option2": "option 2 value"
  }
}

然后我startup.cs我注册选项如下

services.Configure<MyOptions>(Configuration.GetSection("MyOptions"));

dotnet 能够将 IOptions<MyOptions> 注入到 MyService class.

现在,我有集成测试项目。我已将相同的 appsettings.json 复制到集成测试项目中。我想创建 IOptions<MyOptions> 的实例,它从 appsettings.json

加载值
public class MyTestClass
{
    private readonly IConfigurationRoot _config;

    public MyTestClass()
    {                        
        _config = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();
    }

    [Fact]
    public void MyTest()
    {
        // arrange

        // this line returns NULL
        var optionValue  = _config.GetSection("MyOptions").Value;

        // i also tried GetValue which returns NULL as well
        //var optionValue = _config.GetValue<MyOptions>("MyOptions");

        var options = Options.Create<MyOptions>(optionValue);
        var service = new MyService(options);

        //act

        // assert
    }
}

_config.GetSection("MyOptions").Value_config.GetValue<MyOptions>("MyOptions") 都 returns 为空。

当我快速查看 _config 变量时,我看到值是从 appsettings.json 加载的

找到了。我必须绑定实例

var optionValue  = new MyOptions();
_config.GetSection("MyOptions").Bind(optionValue);
 var options = Options.Create<MyOptions>(optionValue);

或者我也可以

 var optionValue = _config.GetSection("MyOptions").Get<MyOptions>();
 var options = Options.Create<MyOptions>(optionValue);