CollectionAssert.AreEqual Failed

I am trying to compare two lists with

CollectionAssert.AreEqual(ListExpected, ListActual); 

But I get 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 null element using Assert.AreEqual in a field by field, everything was fine.

Any idea why I can't compare using CollectionAssert

+8
c # nunit
source share
1 answer

An object is "declared" equal to another object in .NET if its Equals(object other) method returns true. You need to implement this method for your API.Program.Relation class, otherwise .NET will consider your objects different if they are not referenced. The fact that all fields are the same does not matter for .NET: if you need equality semantics for each field, you need to provide an Equals implementation that supports it.

When you override Equals , remember to also override GetHashCode - they must be overridden together.

If you do not want or cannot override Equals for any reason, you can use the CollectionAssert.AreEqual overload , which takes an instance of IComparer , to help compare the items in the collection.

+11
source share

All Articles