如何模拟IOptionsSnapshot实例进行测试

ari*_*its 8 c# unit-testing moq asp.net-core asp.net-core-1.1

我有一个类AbClass与asp.net核心内置的DI实例IOptionsSnapshot<AbOptions>(动态配置).现在我想测试这个课程.

我试图AbClass在测试类中实例化类,但我不知道如何实例化一个IOptionsSnapshot<AbOptions>注入构造函数的实例AbClass.

我试过使用Mock<IOptionsSnapshot<AbOptions>>.Object,但是我需要为这个实例设置一些值,因为在AbClass中代码使用了这个值(var x = _options.cc.D1).

所以我有一个代码

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

但我不知道如何链接此选项和IOptionsSnapshot模拟.

AbClass:

public class AbClass {
    private readonly AbOptions _options;

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

我的测试实例化了这个类:

var service = new AbClass(new Mock???)
Run Code Online (Sandbox Code Playgroud)

并且需要在AbClass该调用中测试一个方法x(),但是ArgumentNullException当它打开时它会抛出_options.cc.D1

Bas*_*lew 12

通用方法:

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

用法:

var mock = CreateIOptionSnapshotMock(new AbOptions(){
    cc = new cc {
        D1 = "https://",
        D2 = "123145854170887"
    }
});
Run Code Online (Sandbox Code Playgroud)


Nko*_*osi 11

您应该能够模拟界面并为测试创建选项类的实例.由于我不知道选项类的嵌套类,我正在做出一个广泛的假设.

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

现在,对嵌套值的访问应该返回正确的值而不是NRE