views:

377

answers:

4

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.

+3  A: 

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

Marc Gravell
+4  A: 

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

Anteru
+1  A: 

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;
}
SDX2000
+2  A: 

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.)
Erix Xu
thank you so much! this worked!
Paintrick