在 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>
注入(inject) 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 加载的最佳答案
找到了。我必须绑定(bind)实例
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);
关于asp.net-core - 如何构建 IOptions<T> 进行测试?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49262906/