Mock IOptionsMonitor
Asked Answered
D

3

33

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.

Duenas answered 2/5, 2019 at 10:58 Comment(2)
learn.microsoft.com/en-us/dotnet/api/…Lotty
In this case I would have just mocked the interfaceLotty
L
34

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);
Lotty answered 2/5, 2019 at 11:51 Comment(0)
R
15

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;
}
Rolfe answered 14/1, 2020 at 13:51 Comment(0)
H
7

Achieving the same in NSubstitute:

        var optionsMonitorMock = Substitute.For<IOptionsMonitor<AuthenticationSettings>>();
        optionsMonitorMock.CurrentValue.Returns(new AuthenticationSettings
        {
            // values go here
        });
Helvellyn answered 29/5, 2020 at 11:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.