如何构建用于测试的IOptions <t>?

时间:2018-03-13 18:01:51

标签: asp.net-core .net-core asp.net-core-2.0 coreclr

在ASP.NET Core 2中,我有以下使用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类。

现在,我有集成测试项目。我已将相同的appsettings.json复制到集成测试项目中。我想创建加载来自appsettings.json

的值的IOptions<MyOptions>实例
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")都返回null。

当我快速观察_config变量时,我看到值是从appsettings.json加载的 enter image description here

1 个答案:

答案 0 :(得分:3)

找到了它。我必须绑定实例

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