如何构建IOptionsMonitor <T>进行测试?

alk*_*djg 6 configuration dependency-injection appsettings .net-core

对于普通的IOptions接口,您可以手动构建实例,例如this SO question

有没有使用DI制作IOptionsMonitor实例的等效方法?

小智 8

您可以执行以下操作,然后将其用于测试:

    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; }
    } 
Run Code Online (Sandbox Code Playgroud)


Eri*_*Dev 6

Hananiel 的回答很好

这是它的通用版本:

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; }
}
Run Code Online (Sandbox Code Playgroud)

只需使用您的对象创建一个实例!