How to compare Lists in Unit Testing
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
}
Solution 1:
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.
Solution 2:
I guess this will help
Assert.IsTrue(expected.SequenceEqual(actual));