【问题标题】:nsubstitute received called with specific object argumentnsubstitute 接收到带有特定对象参数的调用
【发布时间】:2015-08-27 14:01:42
【问题描述】:

我有一个看起来像这样的类:

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(),但我不知道如何解决?

【问题讨论】:

  • this 是一个好的解决方案吗?
  • @w0lf 是和否,我认为它会起作用,但我可能不得不实现IEquatable,因为List&lt;&gt; 可以是除string 之外的其他对象类型的列表,谢谢
  • 你为什么把_realClass_mockedClass搞混了?我没有看到使用expectedArgNames 变量调用CheckArgs() 的代码。您能否发布可重现代码

标签: c# unit-testing nsubstitute


【解决方案1】:

在您的测试中,您将myArguments 类与List&lt;string&gt; 进行比较。

您应该将myArguments.argNamesList&lt;string&gt; 进行比较,或者在myArguments 中实现IEquatable&lt;List&lt;string&gt;&gt;

此外,当您比较List&lt;T&gt; 时,您应该使用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);
    }
}

【讨论】:

  • 使用第二个选项,测试将如下所示:x.ArgNames.Equals(expectedArgNames) 对吗?是的,我忘了包括 x.argNames.Equals
  • 不,第二个选项你会得到x.Equals
  • 对于任何好奇如何将第一个选项解决方案扩展到多个参数的人:stackoverflow.com/a/31316858/3905007
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多