当前位置:  开发笔记 > 编程语言 > 正文

对于类似的自定义类列表,NUnit的CollectionAssert返回false

如何解决《对于类似的自定义类列表,NUnit的CollectionAssert返回false》经验,为你挑选了1个好方法。

这是我的班级:

public class MyClass
{
    public string Name { get; set; }
    public string FaminlyName { get; set; }
    public int Phone { get; set; }
}

然后我有两个相似的列表:

List list1 = new List()
{
    new MyClass() {FaminlyName = "Smith", Name = "Arya", Phone = 0123},
    new MyClass() {FaminlyName = "Jahani", Name = "Shad", Phone = 0123}
};
List list2 = new List()
{
    new MyClass() {FaminlyName = "Smith", Name = "Arya", Phone = 0123},
    new MyClass() {FaminlyName = "Jahani", Name = "Shad", Phone = 0123}
};

问题是NUnit CollectionAssert总是返回false.

CollectionAssert.AreEqual(list1,list2);

我错过了一些关于CollectionAssert测试的内容



1> Willem Van O..:

AreEqual为对象的平等检查.由于您没有覆盖该Equals方法,因此false如果引用不相等,它将返回.

你可以通过覆盖Equals你的方法来解决这个问题MyClass:

public class MyClass {
    public string Name { get; set; }
    public string FaminlyName { get; set; }
    public int Phone { get; set; }

    public override bool Equals (object obj) {
         MyClass mobj = obj as MyClass;
         return mobj != null && Object.Equals(this.Name,mobj.Name) && Object.Equals(this.FaminlyName,mobj.FaminlyName) && Object.Equals(this.Phone,mobj.Phone);
    }

}

您还可以更好地覆盖该GetHashCode方法:

public class MyClass {
    public string Name { get; set; }
    public string FaminlyName { get; set; }
    public int Phone { get; set; }

    public override bool Equals (object obj) {
         MyClass mobj = obj as MyClass;
         return mobj != null && Object.Equals(this.Name,mobj.Name) && Object.Equals(this.FaminlyName,mobj.FaminlyName) && Object.Equals(this.Phone,mobj.Phone);
    }

    public override int GetHashCode () {
        int hc = 0x00;
        hc ^= (this.Name != null) ? this.Name.GetHashCode() : 0;
        hc ^= (this.FaminlyName != null) ? this.FaminlyName.GetHashCode() : 0;
        hc ^= this.Phone.GetHashCode();
        return hc;
    }

}

推荐阅读
有风吹过best
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有