Verifying collections/arrays in MS Unit Testing

If you're using Microsoft's unit testing framework that is built in to VS2008 (and some VS2005 SKU's), you're probably aware of the Assert class.  You use that a lot to make assertions on properties and return values to determine if your unit test passed or failed.

If you try and do an assert on a collection or array (say, an array of doubles), Assert.AreEqual will always return false, even if the contents of the array match.  Example:

   1: [TestMethod]
   2: public void CheckArrays()
   3: {
   4:     double[] array1 = new double[] { 2.0, 3.0, 6.7 };
   5:  
   6:     Assert.AreEqual(new double[] { 2.0, 3.0, 6.7 }, array1);
   7: }

This test results in a failure:

Assert.AreEqual failed. Expected:<System.Double[]>. Actual:<System.Double[]>.

The reason is that with an array, the Assert class is checking for reference equality.  For something simple above you could write three different asserts – one for each element of the array.  But that is too brittle to stand the test of time (or a code review!).  Instead, Microsoft has the CollectionAssert class which will loop through the array and check each element for equality.  If we re-write the test above as:

   1: [TestMethod]
   2: public void CheckArrays()
   3: {
   4:     double[] array1 = new double[] { 2.0, 3.0, 6.7 };
   5:  
   6:     CollectionAssert.AreEqual(new double[] { 2.0, 3.0, 6.7 }, array1);
   7: }

We now get a passing test.

Technorati Tags: ,,

No Comments