我使用NUnit和NSubstitute进行单元测试。我有以下内容:
public interface IDataProvider
{
void Log(int tvmId, DateTime time, int source, int level, int eventCode, string message);
}
...
var fakeDataProvider = Substitute.For<IDataProvider>();
...
fakeDataProvider.Received().Log(
Arg.Any<int>(),
new DateTime(2000, 1, 1),
0,
0,
0,
null);
fakeDataProvider.Received()抛出AmbiguousArgumentException,并显示无法确定要使用的参数规范的消息。我在SO
上找到了以下内容Cannot determine argument specifications to use
这是相关的,但我不能在上面的代码中应用它。为什么上面的代码含糊不清?我怎么能指定Received()它应该接受任何参数?
答案 0 :(得分:7)
由于int
方法中有多个Log
参数,因此必须为每个参数使用参数规范。
fakeDataProvider.Received().Log(
Arg.Any<int>(),
new DateTime(2000, 1, 1),
Arg.Is(0),
Arg.Is(0),
Arg.Is(0),
null);
答案 1 :(得分:0)
好吧,对于年轻玩家的另一个陷阱:如果您在一次测试中多次调用同一方法,请不要在调用之间重复使用参数说明符:
我有一个需要两个 Dictionary
var checkArg1 = Arg.Is<Dictionary<string, MyStruct>>(dico => dico.Count == 0);
var checkArg2 = Arg.Is<Dictionary<string, MyStruct>>(dico => dico.Count == 0);
mySubtitue.Received(1).myMethod(checkArg1, checkArg2);
// do something that triggers another call to MyMethod
// ...
// second check using the same argument specifiers
mySubtitue.Received(1).myMethod(checkArg1, checkArg2);
您仍然会收到“请对所有相同类型的参数使用规范”。
解决方案是在每次参数说明符时实例化:
var checkArg1 = Arg.Is<Dictionary<string, MyStruct>>(dico => dico.Count == 0);
var checkArg2 = Arg.Is<Dictionary<string, MyStruct>>(dico => dico.Count == 0);
mySubtitue.Received(1).myMethod(checkArg1, checkArg2);
// do something that triggers another call to MyMethod
// ...
// second check using new argument specifiers
checkArg1 = Arg.Is<Dictionary<string, MyStruct>>(dico => dico.Count == 0);
checkArg2 = Arg.Is<Dictionary<string, MyStruct>>(dico => dico.Count == 0);
mySubtitue.Received(1).myMethod(checkArg1, checkArg2);
答案 2 :(得分:0)
你可以使用下面的代码来做到这一点
fakeDataProvider.Received().Log(
Arg.Any<int>(),
new DateTime(2000, 1, 1),
Arg.Is(0),
Arg.Is(0),
Arg.Is(0),
null);