Search code examples
c#assertions

What check CollectionAssert.AreEquivalent


I was reading about the method CollectionAssert.AreEquivalent in a MSDN article and according to MSDN:

Two collections are equivalent if they have the same elements in the same quantity, but in any order. Elements are equal if their values are equal, not if they refer to the same object.

I tried the following code in Visual Studio:

var first = new TradeData { ID = "A", MarketPrice = 0 };
var mockFir = new TradeData { ID = "A", MarketPrice = 0 };
var collection = new List<TradeData> { first };
var mockCollection = new List<TradeData> { mockFir };
CollectionAssert.AreEquivalent(collection, mockCollection);

But I got an Exception:

CollectionAssert.AreEquivalent failed

So, my question is: what exactly MSDN mean when they say that "Elements are equal if their values are equal, not if they refer to the same object"?


Solution

  • Because the TradeData class does not override object.Equals, the base implementation takes over, which compares two objects by reference. Although first and mockFir contain the same values they are not the same object and so they are not considered equal. If you override Equals in the TradeData class your example will work.