Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CollectionAssert.AreEqual Failing

Tags:

c#

.net

nunit

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

like image 271
Night Walker Avatar asked Apr 20 '12 18:04

Night Walker


1 Answers

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 your API.Program.Relation class, 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 of Equals that supports it.

When you override Equals, don't forget to override GetHashCode as well - these must be overriden together.

If you do not want to or cannot override Equals for some reason, you could use an overload of CollectionAssert.AreEqual that takes an instance of IComparer to assist in comparing collection elements.

like image 83
Sergey Kalinichenko Avatar answered Sep 21 '22 05:09

Sergey Kalinichenko