I am trying to compare two Lists using
CollectionAssert.AreEqual(ListExpected, ListActual);
But I am getting an exception
Expected and actual are both <System.Collections.Generic.List`1[API.Program.Relation]> with 11 elements
Values differ at index [0]
Expected: <API.Program.Relation>
But was: <API.Program.Relation>
But when I compared the zero element using Assert.AreEqual on field by field everything was fine.
Any idea why I cannot compare using CollectionAssert
An object is “declared” equal to another object in .NET is if its
Equals(object other)method returns true. You need to implement that method for yourAPI.Program.Relationclass, otherwise .NET considers your objects different unless they are reference-equal. The fact that all fields are the same does not matter to .NET: if you need field-by-field equality semantics, you need to provide an implementation ofEqualsthat supports it.When you override
Equals, don’t forget to overrideGetHashCodeas well – these must be overriden together.If you do not want to or cannot override
Equalsfor some reason, you could use an overload ofCollectionAssert.AreEqualthat takes an instance ofIComparerto assist in comparing collection elements.