10

Here's my test function (c#, visual studio 2010):

[TestMethod()]
public void TestGetRelevantWeeks()
{
List<sbyte> expected = new List<sbyte>() { 2, 1, 52, 51, 50, 49, 48, 47, 46, 45 };
List<sbyte> actual = new List<sbyte>() { 2, 1, 52, 51, 50, 49, 48, 47, 46, 45 };
Assert.AreEqual<List<sbyte>>(expected, actual);
}

Exception: Failed TestGetRelevantWeek Assert.AreEqual failed.
Expected:System.Collections.Generic.List 1[System.SByte].
Actual:System.Collections.Generic.List 1[System.SByte].


Does AreEqual only check equality of the reference, not the contents?

But then, the exception message would be confusing. I also couldn't find a documentation of the default equality comparer for a generic list.

Could you help to clarify why the test fails and what would be solutions for testing the equality of the contents of both lists?

Kind regards

nabulke
  • 11,025
  • 13
  • 65
  • 114
  • The *default* on classes is always reference equality. The lack of any documentation to the contrary usually means the default still applies. – Marc Gravell Feb 22 '11 at 08:31

5 Answers5

19

The Assert.AreEqual() method does a reference equality test as you expected.

Assuming you're using .Net 3.5 or above, you can do this:

using System.Linq;

Assert.IsTrue(expected.SequenceEqual(actual));

Edit: Clarified when this option is available.

Jackson Pope
  • 14,520
  • 6
  • 56
  • 80
13

Does AreEqual only check equality of the reference, not the contents?

Yeap.

To test the contents you could:

Assert.AreEqual(expected.Count, actual.Count);
for (var i = 0; i < expected.Count; i++)
{
    Assert.AreEqual(expected[i], actual[i]);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks for your help. I accepted you answer because SequenceEqual(...) in the other answers is not supported by List<> generic collections. Your solutions works :-) – nabulke Feb 22 '11 at 11:59
  • 1
    @nabulke: It is if you're targetting the .Net 3.5 framework or above and you have `using System.Linq;` in your file. But you're right, Darin's answer will always work. – Jackson Pope Feb 22 '11 at 14:04
5

I think that this is what your are looking for:

Assert.IsTrue(expected.SequenceEqual(actual));

Check this question

Community
  • 1
  • 1
Morvader
  • 2,317
  • 3
  • 31
  • 44
2

You can also use CollectionAssert instead of Assert:

CollectionAssert.AreEqual(expected, actual);

I think it is much more simple and fancier than a loop over the collection of your test cases.

סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68
0
CollectionAssert.AreEqual(expected, actual);
Assert.IsTrue(expected.SequenceEqual(actual));
Assert.IsTrue(expected.SequenceEqual(actual));

These options don't work for me.

Probably the only viable option. Had to use this:

for (var i = 0; i < expected.Count; i++)
        {
            Assert.AreEqual(expected[i], actual[i]);
        }
Bl1c
  • 1
  • 1