c# - nsubstitute 收到调用特定对象参数

标签 c# unit-testing 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() 但我不确定如何解决它?

最佳答案

在您的测试中,您正在比较 myArgumentsList<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);
    }
}

关于c# - nsubstitute 收到调用特定对象参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32251485/

相关文章:

c# - 将数据从Mongodb转换为MySQL(110M docs,60 Gigs)-提示和建议?

c# - 如何在单元测试中模拟 HttpRequest 的 UserAgent 属性?

c# - 当参数不完全匹配时模拟成员调用

c# - AutoSuggestBox 显示属性名称而不是值

c# - 从 C# 中提取 Word 文档中的宏到文本文件

c# - 如何从 MVC4 中的 View 编辑父项的属性?

unit-testing - 单元测试Automapper配置文件

unit-testing - 如何在自定义文件夹中使用 go test 生成多个包的覆盖率?

c# - 如何使用 NSubstitute 替换 Object.ToString?

c# - 根据对象的属性而不是其引用模拟设置返回类型