2015-08-27 44 views
3

我有一個類,它看起來是這樣的:nsubstitute收到調用特定對象參數

public myArguments 
{ 
    public List<string> argNames {get; set;} 
} 

在我的測試我這樣做:

var expectedArgNames = new List<string>(); 
expectedArgNames.Add("test"); 

_mockedClass.CheckArgs(Arg.Any<myArguments>()).Returns(1); 

_realClass.CheckArgs(); 

_mockedClass.Received().CheckArgs(Arg.Is<myArguments>(x => x.argNames.Equals(expectedArgNames)); 

但測試失敗,此錯誤消息:

NSubstitute.Exceptions.ReceivedCallsException : Expected to receive a call matching: 
    CheckArgs(myArguments) 
Actually received no matching calls. 
Received 1 non-matching call (non-matching arguments indicated with '*' characters): 
    CheckArgs(*myArguments*) 

我猜這是因爲.Equals()的,但我不知道如何解決呢?

+0

是[此](http://stackoverflow.com/a/12699199/390819)很好地解決? – GolfWolf

+0

@ w0lf是和不,我認爲它會工作,但我可能將不得不實現'IEquatable',因爲'List <>'可以是'string'之外的其他對象類型列表,謝謝 – SOfanatic

+0

爲什麼你混淆了'_realClass'和'_mockedClass'?我看不到用'expectedArgNames'變量調用'CheckArgs()'的代碼。你可以發佈**可重現的**代碼 –

回答

4

在測試中,您將myArguments類與List<string>進行比較。

您應該比較myArguments.argNamesList<string>或實施IEquatable<List<string>>myArguments

此外,當您比較List<T>時,應該使用SequenceEquals而不是Equals

第一種選擇將是:

_mockedClass.Received().CheckArgs(
    Arg.Is<myArguments>(x => x.argNames.SequenceEqual(expectedArgNames))); 

第二是:

public class myArguments : IEquatable<List<string>> 
{ 
    public List<string> argNames { get; set; } 

    public bool Equals(List<string> other) 
    { 
     if (object.ReferenceEquals(argNames, other)) 
      return true; 
     if (object.ReferenceEquals(argNames, null) || object.ReferenceEquals(other, null)) 
      return false; 

     return argNames.SequenceEqual(other); 
    } 
} 
+0

第二個選項的測試看起來像這樣:'x.ArgNames.Equals(expectedArgNames)'是嗎?是的,我忘了包含'x.argNames.Equals'。 – SOfanatic

+0

不,第二種選擇是'''x.Equals'''。 –