Night Walker
Night Walker

Reputation: 21260

CollectionAssert.AreEqual Failing

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

Upvotes: 9

Views: 5763

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

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.

Upvotes: 12

Related Questions