模拟IOptionsMonitor

Olo*_*f84 6 c# integration-testing options asp.net-core asp.net-core-2.2

如何在构造函数中手动创建需要IOptionsMonitor的类的类实例?

我的课

private readonly AuthenticationSettings _authenticationSettings;

public ActiveDirectoryLogic(IOptionsMonitor<AuthenticationSettings> authenticationSettings)
{            
   _authenticationSettings = authenticationSettings.CurrentValue;
}
Run Code Online (Sandbox Code Playgroud)

我的测试

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

我试图手动制作一个IOptionsMonitor对象,但不知道如何做。

Rob*_*ert 7

这是另一种不涉及尝试设置只读 CurrentValue 字段的方法。

using Moq;

private IOptionsMonitor<AppConfig> GetOptionsMonitor(AppConfig appConfig)
{
  var optionsMonitorMock = new Mock<IOptionsMonitor<AppConfig>>();
  optionsMonitorMock.Setup(o => o.CurrentValue).Returns(appConfig);
  return optionsMonitorMock.Object;
}
Run Code Online (Sandbox Code Playgroud)


Tja*_*art 6

在 NSubstitute 中实现相同的效果:

        var optionsMonitorMock = Substitute.For<IOptionsMonitor<AuthenticationSettings>>();
        optionsMonitorMock.CurrentValue.Returns(new AuthenticationSettings
        {
            // values go here
        });
Run Code Online (Sandbox Code Playgroud)


Nko*_*osi 5

您正在OptionsMonitor<TOptions>错误地调用类的构造函数。

在这种情况下,我只会嘲笑 IOptionsMonitor<AuthenticationSettings>界面

例如使用最小起订量

AuthenticationSettings au = new AuthenticationSettings() { ... };
var monitor = Mock.Of<IOptionsMonitor<AuthenticationSettings>>(_ => _.CurrentValue == au);
ActiveDirectoryLogic _SUT = new ActiveDirectoryLogic(monitor);
Run Code Online (Sandbox Code Playgroud)