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

孤者浪人 提交于 2021-02-05 06:33:40

问题


Here is my class:

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

Then I have two similar list:

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

The problem is that NUnit CollectionAssert return false always.

CollectionAssert.AreEqual(list1,list2);

Am I missing something about CollectionAssert test


回答1:


The AreEqual checks for equality of the objects. Since you did not override the Equals method, it will return false in case the references are not equal.

You can solve this by overriding the Equals method of your 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);
    }

}

You furthermore better override the GetHashCode method as well:

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

}


来源:https://stackoverflow.com/questions/34382277/nunits-collectionassert-return-false-for-similar-lists-of-custom-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!