NUnit 的 CollectionAssert return false 对于类似的自定义列表 class

NUnit's CollectionAssert return false for similar lists of custom class

这是我的 class:

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

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

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

问题是 NUnit CollectionAssert return 总是错误的。

CollectionAssert.AreEqual(list1,list2);

我是否遗漏了有关 CollectionAssert 测试的内容

AreEqual 检查对象是否相等。由于您没有覆盖 Equals 方法,它会 return false 以防 references 不相等。

您可以通过重写 MyClassEquals 方法来解决此问题:

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;
    }

}