Testing collections with NUnit

How do you test collections for equality of their elements? I often used to write my own custom assert for that, something like:

public void AssertCollectionElementsAreEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual)
{
    var first = expected.GetEnumerator();
    var second = actual.GetEnumerator();
    int count = 0;
    while(first.MoveNext())
    {
        if(second.MoveNext())
        {
            Assert.AreEqual(first.Current,second.Current);
        }
        else
        {
            throw new AssertionException(string.Format("Collection has less elements than expected: {0}", count));
        }
        count++;
    }
    if(second.MoveNext())
    {
        throw new AssertionException(string.Format("Collection has more elements than expected."));
    }
}

I thought it’s just plain to common task to not be included in the framework itself, so I read the manual, and I found CollectionAssert.AreEqual() method that does exactly that.

Then Charlie Poole, made me realize there is even simpler way.

using System.Collections.Generic;
using NUnit.Framework;
 
namespace NUnitAreEqualSample
{
    [TestFixture]
    public class CollectionsEqualitySampleTests
    {
        [Test]
        public void DifferentTypesOfCollectionsShoudBeEqualIfElementsAreEqual()
        {
            var list = new List<string> {"foo", "bar"};
            var array = new[] {"foo", "bar"};
            Assert.AreEqual(list, array);//notice this
        }
    }
}

This produces following result:

nunit_areEqual_passed

Simple Assert.AreEqual() does the job. Sweet.

Technorati Tags: , ,
  • Tuna Toksoz

    I’d prefer the explicit way, Assert.AreEqual doesn’t sound good to me.