Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I build an IOptionsMonitor<T> for testing?

For the normal IOptions interface, you can manually build an instance e.g. this SO question.

Is there any equivalent way to make an IOptionsMonitor instance without using DI?

like image 234
alksdjg Avatar asked Dec 04 '18 01:12

alksdjg


People also ask

Is IOptionsMonitor a singleton?

IOptionsMonitor is a Singleton service that retrieves current option values at any time, which is especially useful in singleton dependencies.

How do you inject IOptionsMonitor?

You need to create a class with MyOptions[] as a property and the inject that class and add the whole configuration without section.


2 Answers

nice answer from Hananiel

Here the generic version of it:

public class TestOptionsMonitor<T> : IOptionsMonitor<T>
    where T : class, new()
{
    public TestOptionsMonitor(T currentValue)
    {
        CurrentValue = currentValue;
    }

    public T Get(string name)
    {
        return CurrentValue;
    }

    public IDisposable OnChange(Action<T, string> listener)
    {
        throw new NotImplementedException();
    }

    public T CurrentValue { get; }
}

and simply create an instance with your object!

like image 58
EricBDev Avatar answered Sep 28 '22 05:09

EricBDev


You can do something like below and and then use that for testing:

    public class TestOptionsMonitor : IOptionsMonitor<MyOptions>
    {
        public TestOptionsMonitor(MyOptions currentValue)
        {
            CurrentValue = currentValue;
        }

        public MyOptions Get(string name)
        {
            return CurrentValue;
        }

        public IDisposable OnChange(Action<MyOptions, string> listener)
        {
            throw new NotImplementedException();
        }

        public MyOptions CurrentValue { get; }
    } 
like image 33
Hananiel Avatar answered Sep 28 '22 05:09

Hananiel