AssertFailedException: CollectionAssert.AreEqual failed (Element at index 0 do not match)

Артур Кузнецов 21 Reputation points
2022-04-25T12:12:16.617+00:00

Why this method fails with message: "CollectionAssert.AreEqual failed. (Element at index 0 do not match.)"?

[TestMethod]
        public void Listest()
        {
            List<int[]> first = new List<int[]>()
            {
                new int[] { 1, 3, 5 }
            };

            List<int[]> second = new List<int[]>()
            {
                new int[] { 1, 3, 5 }
            };
            CollectionAssert.AreEqual(first, second);
        }

But code below works fine:

[TestMethod]
        public void Listest()
        {
            int[] arr = new int[] { 1, 3, 5 };
            List<int[]> first = new List<int[]>()
            {
                arr
            };

            List<int[]> second = new List<int[]>()
            {
                arr
            };
            CollectionAssert.AreEqual(first, second);
        }
Visual Studio Testing
Visual Studio Testing
Visual Studio: A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.Testing: The act or process of applying tests as a means of analysis or diagnosis.
337 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 51,341 Reputation points
    2022-04-25T14:35:39.567+00:00

    Because the first test is a list of arrays. Arrays are reference types and the only way for first[0] to be equal to second[0] is if they are the same object. Reference types follow reference semantics meaning 2 objects are equal only if they are the same object.

    In the second test you are using the same array in both lists. Since first[0] is the same array/object as second[0] then they are equal. You can confirm they are the same object by changing an element (e.g. arr[1] to 10). Both lists will see the change because they both have the same object in their list.

    Refer to the docs here on how equality works in .NET.


0 additional answers

Sort by: Most helpful