Aryan Firouzian
Aryan Firouzian

Reputation: 2026

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

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

Upvotes: 3

Views: 1323

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

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

}

Upvotes: 5

Related Questions