How to compare Lists in Unit Testing

C#Visual Studio-2010Unit TestingMstest

C# Problem Overview


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
}

C# Solutions


Solution 1 - C#

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 - C#

I guess this will help

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

Solution 3 - C#

If you want to check that each contains the same collection of values then you should use:

CollectionAssert.AreEquivalent(expected, actual);

Edit: >"Two collections are equivalent if they have the same elements in the same quantity, but in any order. Elements are equal if their values are equal, not if they refer to the same object." - https://msdn.microsoft.com/en-us/library/ms243779.aspx

Solution 4 - C#

I tried the other answers in this thread, and they didn't work for me and I was comparing collections of objects that had the same values stored in their properties, but the objects were different.

Method Call :

CompareIEnumerable(to, emailDeserialized.ToIndividual,
            (x, y) => x.ToName == y.ToName && x.ToEmailAddress == y.ToEmailAddress);

Method for comparisons:

private static void CompareIEnumerable<T>(IEnumerable<T> one, IEnumerable<T> two, Func<T, T, bool> comparisonFunction)
    {
        var oneArray = one as T[] ?? one.ToArray();
        var twoArray = two as T[] ?? two.ToArray();

        if (oneArray.Length != twoArray.Length)
        {
            Assert.Fail("Collections are not same length");
        }

        for (int i = 0; i < oneArray.Length; i++)
        {
            var isEqual = comparisonFunction(oneArray[i], twoArray[i]);
            Assert.IsTrue(isEqual);
        }
    }

Solution 5 - C#

this test compares a date input, checks if its a leap year, if so, outputs 20 leap years from the inputted date, if not, outputs the NEXT 20 leap years, myTest.Testing refers to the myTest instance which in turn calls the values from a List called Testing containing the calculated values required. part of an exercise I had to do.

[TestMethod]
        public void TestMethod1()
        {
            int testVal = 2012;
            TestClass myTest = new TestClass();
            var expected = new List<int>();
            expected.Add(2012);
            expected.Add(2016);
            expected.Add(2020);
            expected.Add(2024);
            expected.Add(2028);
            expected.Add(2032);
            expected.Add(2036);
            expected.Add(2040);
            expected.Add(2044);
            expected.Add(2048);
            expected.Add(2052);
            expected.Add(2056);
            expected.Add(2060);
            expected.Add(2064);
            expected.Add(2068);
            expected.Add(2072);
            expected.Add(2076);
            expected.Add(2080);
            expected.Add(2084);
            expected.Add(2088);
            var actual = myTest.Testing(2012);
            CollectionAssert.AreEqual(expected, actual);
        }

Solution 6 - C#

Fluent assertions does deep comparisons of arrays actualArray.Should().BeEquivalentTo(expectedArray)

Solution 7 - C#

List<AdminUser> adminDetailsExpected = new List<AdminUser>()
{
new AdminUser  {firstName = "test1" , lastName = "test1" , userId = 
"001test1"  },
new AdminUser {firstName = "test2" , lastName = "test2" , userId = 
"002test2"   }
};

//Act

List<AdminUser> adminDetailsActual = RetrieveAdmin(); // your retrieve logic goes here

//Assert

Assert.AreEqual(adminDetailsExpected.Count, adminDetailsActual.Count);  //Test succeeds if the count matches else fails. This count can be used as a work around to test

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRay ChengView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#ShyjuView Answer on Stackoverflow
Solution 3 - C#topham101View Answer on Stackoverflow
Solution 4 - C#DeclanView Answer on Stackoverflow
Solution 5 - C#gettingThereSlowlyView Answer on Stackoverflow
Solution 6 - C#Ram PratapView Answer on Stackoverflow
Solution 7 - C#karthik kasubhaView Answer on Stackoverflow