Assert that arrays are equal in Visual Studio 2008 test framework

C#Visual Studio-2008Unit Testing

C# Problem Overview


Is there an easy way to check in a unit test that two arrays are equal (that is, have the same number of elements, and each element is the same?).

In Java, I would use assertArrayEquals (foo, bar);, but there seems to be no equivalent for C#. I tried Assert.AreEqual(new string[]{"a", "b"}, MyFunc("ab"));, but even though the function returns an array with "a", "b" the check still fails

This is using Visual Studio 2008 Team Suite, with the built-in unit test framework.

C# Solutions


Solution 1 - C#

It's CollectionAssert.AreEqual, see also the documentation for CollectionAssert.

Solution 2 - C#

Class1.cs:


namespace ClassLibrary1
{
public class Class1
{
Array arr1 = new[] { 1, 2, 3, 4, 5 };
public Array getArray()
{
return arr1;
}
}
}

ArrayEqualTest.cs:


[TestMethod()]
public void getArrayTest()
{
Class1 target = new Class1();
Array expected = new []{1,2,3,4,5};
Array actual;
actual = target.getArray();
CollectionAssert.AreEqual(expected, actual);
//Assert.IsTrue(expected.S actual, "is the test results");
}

Test Success,found the error:


CollectionAssert.AreEqual failed. (Element at index 3 do not match.)

Solution 3 - C#

In .NET 3.5, perhaps consider Assert.IsTrue(foo.SequenceEqual(bar)); - it won't tell you at what index it differs, though.

Solution 4 - C#

Ok here is a slightly longer way of doing it...

static void Main(string[] args)
{
    var arr1 = new[] { 1, 2, 3, 4, 5 };
    var arr2 = new[] { 1, 2, 4, 4, 5 };

    Console.WriteLine("Arrays are equal: {0}", equals(arr1, arr2));
}

private static bool equals(IEnumerable arr1, IEnumerable arr2)
{

    var enumerable1 = arr1.OfType<object>();
    var enumerable2 = arr2.OfType<object>();

    if (enumerable1.Count() != enumerable2.Count())
        return false;

    var iter1 = enumerable1.GetEnumerator();
    var iter2 = enumerable2.GetEnumerator();

    while (iter1.MoveNext() && iter2.MoveNext())
    {
        if (!iter1.Current.Equals(iter2.Current))
            return false;
    }
                
    return true;
}

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
QuestionAnteruView Question on Stackoverflow
Solution 1 - C#AnteruView Answer on Stackoverflow
Solution 2 - C#Erix XuView Answer on Stackoverflow
Solution 3 - C#Marc GravellView Answer on Stackoverflow
Solution 4 - C#AutodidactView Answer on Stackoverflow