I want to assert that the elements of two list contains values that I expected, something like:
var foundCollection = fooManager.LoadFoo();
var expectedCollection = new List<Foo>()
{
new Foo() { Bar = "a", Bar2 = "b" },
new Foo() { Bar = "c", Bar2 = "d" }
};
//assert: I use AreEquivalent since the order does not matter
CollectionAssert.AreEquivalent(expectedCollection, foundCollection);
However the above code will not work (I guess because .Equals() does not return true for different objects with the same value). In my test, I only care about the public property values, not whether the objects are equal. What can I do to make my assertion?
REWORKED ANSWER
There is a
CollectionAssert.AreEqual(IEnumerable, IEnumerable, IComparer)overload to assert that two collections contain the same objects in the same order, using anIComparerimplementation to check the object equivalence.In the scenario described above, the order is not important. However, to sufficiently handle also the situation where there are multiple equivalent objects in the two collections, it becomes necessary to first order the objects in each collection and use one-by-one comparison to ensure that also the number of equivalent objects are the same in the two collections.
Enumerable.OrderByprovides an overload that takes anIComparer<T>argument. To ensure that the two collections are sorted in the same order, it is more or less required that the types of the identifying properties implementIComparable. Here is an example of a comparer class that implements both theIComparerandIComparer<Foo>interfaces, and where it is assumed thatBartakes precedence when ordering:To assert that the objects in the two collections are the same and comes in equal numbers (but not necessarily in the same order to begin with), the following lines should do the trick: