问题
In ASP.NET Core 2 i have the following class that takes 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"
}
}
Then i startup.cs i register options as below
services.Configure<MyOptions>(Configuration.GetSection("MyOptions"));
dotnet is able to inject IOptions<MyOptions>
into MyService class.
Now, i have integration test project. and i have copied the same appsettings.json into integration test project. I want to create instance of IOptions<MyOptions>
that loads the values from 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
and _config.GetValue<MyOptions>("MyOptions")
both returns null.
when i do quick watch on _config
variable i see the values are loaded from appsettings.json
回答1:
found it. i have to bind the instance
var optionValue = new MyOptions();
_config.GetSection("MyOptions").Bind(optionValue);
var options = Options.Create<MyOptions>(optionValue);
or i can also do
var optionValue = _config.GetSection("MyOptions").Get<MyOptions>();
var options = Options.Create<MyOptions>(optionValue);
来源:https://stackoverflow.com/questions/49262906/how-to-build-ioptionst-for-testing