[英]NSubstitute cannot determine argument specifications to use
我使用 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 上找到了以下內容
這是相關的,但我不能在上面的代碼中應用它。 為什么上面的代碼有歧義? 我還能如何向 Received() 指定它應該接受任何參數?
由於Log
方法中有多個int
參數,因此您必須對每個參數使用參數規范。
fakeDataProvider.Received().Log(
Arg.Any<int>(),
new DateTime(2000, 1, 1),
Arg.Is(0),
Arg.Is(0),
Arg.Is(0),
null);
好吧,年輕玩家的另一個陷阱:如果您在一次測試中多次調用同一方法,請不要在調用之間重用參數說明符:
我有一個需要兩個 Dictionary<string, MyStruct> 的虛擬方法:
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);
您可以使用下面的代碼來做到這一點
fakeDataProvider.Received().Log(
Arg.Any<int>(),
new DateTime(2000, 1, 1),
Arg.Is(0),
Arg.Is(0),
Arg.Is(0),
null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.