Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a mock instance of IOptions<MyOption>?

I'm using IOptions<> according to https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options.

I have the following controller.

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;
    }

Now I'm creating a unit test setup. How to mock 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);
like image 941
ca9163d9 Avatar asked Jan 16 '18 18:01

ca9163d9


2 Answers

Use helper class Microsoft.Extensions.Options.Options

Try replacing

option = new Options<MyOptions>(); 

with

option = Options.Create(new MyOptions());
like image 84
Ehsan Ullah Nazir Avatar answered Nov 13 '22 21:11

Ehsan Ullah Nazir


What about:

var optionsMock = new Mock<IOptions<MyOptions>>();
optionsMock.SetupGet(o => o.Value).Returns(new MyOptions());
like image 12
Stef Heyenrath Avatar answered Nov 13 '22 20:11

Stef Heyenrath