How to make fun of an instance of IOptionsSnapshot for testing

I have a class AbClassthat has a built-in DI instance in asp.net core IOptionsSnapshot<AbOptions>(dynamic configuration). Now I want to test this class.

I am trying to instantiate a class AbClassin a test class, but I do not know how I can create an instance IOptionsSnapshot<AbOptions>to be inserted into the constructor AbClass.

I tried to use it Mock<IOptionsSnapshot<AbOptions>>.Object, but I need to set some values ​​for this instance, since in AbClass the code uses these values ​​( var x = _options.cc.D1).

so I have code like

var builder = new ConfigurationBuilder();
builder.AddInMemoryCollection(new Dictionary<string, string>
{
    ["Ab:cc:D1"] = "https://",
    ["Ab:cc:D2"] = "123145854170887"
});
var config = builder.Build();
var options = new AbOptions();
config.GetSection("Ab").Bind(options);

but I don’t know how to link these parameters and the IOptionsSnapshot layout.

AbClass:

public class AbClass {
    private readonly AbOptions _options;

    public AbClass(IOptionsSnapshot<AbOptions> options) {
        _options = options.Value;    
    }
    private void x(){var t = _options.cc.D1}
}

my test creates an instance of this class:

var service = new AbClass(new Mock???)

AbClass, x(), ArgumentNullException, _options.cc.D1

+6
2

. , .

: IOptionsSnapshot

//Arrange
//Instantiate options and nested classes
//making assumptions here about nested types
var options = new AbOptions(){
    cc = new cc {
        D1 = "https://",
        D2 = "123145854170887"
    }
};
var mock = new Mock<IOptionsSnapshot<AbOptions>>();
mock.Setup(m => m.Value).Returns(options);

var service = new AbClass(mock.Object);

NRE

+9

:

    public static IOptionsSnapshot<T> CreateIOptionSnapshotMock<T>(T value) where T : class, new()
    {
        var mock = new Mock<IOptionsSnapshot<T>>();
        mock.Setup(m => m.Value).Returns(value);
        return mock.Object;
    }

:

var mock = CreateIOptionSnapshotMock(new new AbOptions(){
    cc = new cc {
        D1 = "https://",
        D2 = "123145854170887"
    }
});
0

Source: https://habr.com/ru/post/1663567/


All Articles