Search code examples
c#asp.net-coreintegration-testingasp.net-core-2.2

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.


Solution

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