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: ,,
Published Monday, November 24, 2008 8:31 PM by PSteele
Filed under: ,

Comments

# re: Verifying collections/arrays in MS Unit Testing

Thanks for the tip!

Thursday, November 27, 2008 8:11 AM by Lone Sloane

# Comparing Two Arrays

I was looking at some old code today that was checking if two byte arrays had the same data in them.&#160;

Thursday, July 09, 2009 9:19 PM by Patrick Steele's .NET Blog

# Comparing Two Arrays

I was looking at some old code today that was checking if two byte arrays had the same data in them.&#160;

Thursday, July 09, 2009 9:32 PM by Patrick Steele

# Comparing Two Arrays | I love .NET!

Pingback from  Comparing Two Arrays | I love .NET!

Thursday, July 09, 2009 10:26 PM by Comparing Two Arrays | I love .NET!