Comparing Two objects using Assert.AreEqual()

Vishweshwar Kapse picture Vishweshwar Kapse · Mar 21, 2013 · Viewed 67.9k times · Source

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?

Answer

a-1 picture a-1 · Sep 13, 2013

These answers are far too complicated for the issue. There are no overrides necessary to compare two Lists, and you do not need to break out multiple asserts. Microsoft uses the following class, CollectionAssert.

CollectionAssert.AreEqual(expectedList, actualList)

This works for Lists, Dictionaries, and whatever else implements ICollection interface.

The microsoft documentation is at the following location and details the various types of assertions which can be made on collections

http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.collectionassert.aspx

However, as mentioned by @Bart, this does not work as expected on Lists of (complex) Objects, and the Equals method may still need to be overwritten for those cases.