【发布时间】:2020-04-24 09:38:18
【问题描述】:
我有一个需要字符串集合并且我想模拟的方法:
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 的调用就会返回默认值 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);
【问题讨论】:
标签: c# unit-testing mocking nsubstitute