我根据https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options使用IOptions<>
。
我有以下控制器。
using Microsoft.Extensions.Options;
public class MyController : Controller
{
private readonly ILogger<SourceController> _logger;
private readonly MyOptions _option;
public SourceController(ILogger<SourceController> logger, IOptions<SyncOptions> optionAccessor)
{
_logger = logger;
_option = optionAccessor.Value;
}
现在我正在创建一个单元测试设置。如何模拟IOptions()?
MyTest() { // Test constructor
var loggerFactory = new LoggerFactory().AddConsole(LogLevel.Information).AddDebug().AddNLog();
loggerFactory.ConfigureNLog("nlog.config");
logger = loggerFactory.CreateLogger<MyController>();
option = new Options<MyOptions>(); // Error! How to mock IOptions<MyOptions>()?
app = new MyController(logger, option);
答案 0 :(得分:8)
使用帮助程序类Microsoft.Extensions.Options.Options
尝试替换
option = new Options<MyOptions>();
带
option = Options.Create(new MyOptions());
答案 1 :(得分:7)
那:
var optionsMock = new Mock<IOptions<MyOptions>>();
optionsMock.SetupGet(o => o.Value).Returns(new MyOptions());