How to compare Lists in Unit Testing

Ray Cheng picture Ray Cheng · Jun 15, 2012 · Viewed 93.9k times · Source

How can this test fail?

[TestMethod]
public void Get_Code()
{
    var expected = new List<int>();
    expected.AddRange(new [] { 100, 400, 200, 900, 2300, 1900 });

    var actual = new List<int>();
    actual.AddRange(new [] { 100, 400, 200, 900, 2300, 1900 });

    Assert.AreEqual(expected, actual);
    // Assert.AreSame(expected, actual)       fails
    // Assert.IsTrue(expected.Equals(actual)) fails
}

Answer

Jon Skeet picture Jon Skeet · Jun 15, 2012

To make assertions about collections, you should use CollectionAssert:

CollectionAssert.AreEqual(expected, actual);

List<T> doesn't override Equals, so if Assert.AreEqual just calls Equals, it will end up using reference equality.