模拟方法需要一个列表

mock method expecting a list

我有一个方法需要一个字符串集合并且我想模拟它:

bool DoSomething(IEnumerable<string> myList) { ... }

我想模拟对该方法的每次调用,该方法具有包含以下项目的任何集合:["DLKM"],无论集合的类型是数组、列表还是其他类型。

因此我使用 NSubstitute 创建了一个参数匹配器:

var modellarten = Arg.Is<IEnumerable<string>>(x => !new[] { "DLKM" }.Except(x).Any());

这匹配任何仅包含字符串 "DLKM" 的字符串集合。

这是我的模拟:

var mock = Substitute.For<IMyInterface>();
mock.DoSomething(modellarten).Returns(true);

然而,一旦我使用相同的 arg-matcher 模拟多个方法,对 DoSomething returns 的默认值 false:

的调用
var mock = Substitute.For<IMyInterface>();
mock.Init(modellarten).Returns(true);
mock.DoSomething(modellarten).Returns(true);

所以我想这与匹配器中的闭包有关。但是我不知道如何在不重复 modellarten:

的代码的情况下模拟这两种方法
var mock = Substitute.For<IMyInterface>();
mock.Init(Arg.Is<IEnumerable<string>>(x => !new[] { "DLKM" }.Except(x).Any())).Returns(true);
mock.DoSomething(Arg.Is<IEnumerable<string>>(x => !new[] { "DLKM" }.Except(x).Any())).Returns(true);

与其将匹配器放入单个变量中,不如将代码提取到您在每个 mock 上调用的方法中:

IMyInterface MockInterface()
{
    var mock = Substitute.For<IMyInterface>();
    mock.Init(MatchCollection()).Returns(true);
    mock.DoSomething(MatchCollection()).Returns(true);
    return mock;
}
IEnumerable<string> MatchCollection() 
{
    return Arg.Is<IEnumerable<string>>(x => !new[] { "DLKM" }.Except(x).Any());
}

这将在每次调用时创建一个新的匹配器,而不是使用之前创建的匹配器。