How to build IOptions<T> for testing?
Asked Answered
M

1

5

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 enter image description here

Manumission answered 13/3, 2018 at 18:1 Comment(0)
M
7

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);
Manumission answered 13/3, 2018 at 18:41 Comment(1)
You must add Microsoft.Extensions.Configuration.Binder nuget package to have Bind or Get extension methodEellike

© 2022 - 2024 — McMap. All rights reserved.