Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock IOptionsMonitor

How can I make an class instance manually of a class that requires an IOptionsMonitor in the constructor?

My Class

private readonly AuthenticationSettings _authenticationSettings;

public ActiveDirectoryLogic(IOptionsMonitor<AuthenticationSettings> authenticationSettings)
{            
   _authenticationSettings = authenticationSettings.CurrentValue;
}

My test

AuthenticationSettings au = new AuthenticationSettings(){ ... };
var someOptions = Options.Create(new AuthenticationSettings());
var optionMan = new OptionsMonitor(someOptions);  // dont work.           
ActiveDirectoryLogic _SUT = new ActiveDirectoryLogic(au);

I tried to make an IOptionsMonitor object manually but can't figure out how.

like image 432
Olof84 Avatar asked May 02 '19 10:05

Olof84


3 Answers

You are calling the constructor of the OptionsMonitor<TOptions> class incorrectly.

In this case I would have just mocked the IOptionsMonitor<AuthenticationSettings> interface

For example using Moq

AuthenticationSettings au = new AuthenticationSettings() { ... };
var monitor = Mock.Of<IOptionsMonitor<AuthenticationSettings>>(_ => _.CurrentValue == au);
ActiveDirectoryLogic _SUT = new ActiveDirectoryLogic(monitor);
like image 158
Nkosi Avatar answered Nov 18 '22 09:11

Nkosi


Here is another way to do it that doesn't involve trying to set the readonly CurrentValue field.

using Moq;

private IOptionsMonitor<AppConfig> GetOptionsMonitor(AppConfig appConfig)
{
  var optionsMonitorMock = new Mock<IOptionsMonitor<AppConfig>>();
  optionsMonitorMock.Setup(o => o.CurrentValue).Returns(appConfig);
  return optionsMonitorMock.Object;
}
like image 38
Robert Avatar answered Nov 18 '22 10:11

Robert


Achieving the same in NSubstitute:

        var optionsMonitorMock = Substitute.For<IOptionsMonitor<AuthenticationSettings>>();
        optionsMonitorMock.CurrentValue.Returns(new AuthenticationSettings
        {
            // values go here
        });
like image 6
Tjaart Avatar answered Nov 18 '22 11:11

Tjaart