Search code examples
c#unit-testingobjectcomparexunit

Comparing Two objects using Assert.AreEqual()


I 'm writing test cases for the first time in visual studio c# i have a method that returns a list of objects and i want to compare it with another list of objects by using the Assert.AreEqual() method.

I tried doing this but the assertion fails even if the two objects are identical.

I wanted to know if this method, the two parameters are comparing references or the content of the object,

Do I have to overload the == operator to make this work?


Solution

  • If you are using NUnit this is what the documentation says

    Starting with version 2.2, special provision is also made for comparing single-dimensioned arrays. Two arrays will be treated as equal by Assert.AreEqual if they are the same length and each of the corresponding elements is equal. Note: Multi-dimensioned arrays, nested arrays (arrays of arrays) and other collection types such as ArrayList are not currently supported.

    In general if you are comparing two objects and you want to have value based equality you must override the Equals method.

    To achieve what you are looking for try something like this:

    class Person 
    {
        public string Firstname {get; set;}
        public string Lastname {get; set;} 
    
        public override bool Equals(object other) 
        {
          var toCompareWith = other as Person;
          if (toCompareWith == null) 
            return false;
          return this.Firstname ==  toCompareWith.Firstname && 
              this.Lastname ==  toCompareWith.Lastname; 
        }
    }  
    

    and in your unit test:

    Assert.AreEqual(expectedList.ToArray(), actualList.ToArray());