CollectionAssert to compare lists in a unit test

Categories: .Net   C#   code   collection   kata   Training   training

Working on a code kata last night, I had to return a List<int>.  As is my usual habit for unit tests, I did something similar to:

[code language=”csharp”] [TestMethod] public void PrimeFactorsOfTwo() { List expected = new List() { 2 }; List actual = Class1.FactorNumber(2); Assert.AreEqual(expected, actual,”Prime factors of 2 should be 2. “); } [/code]

I then spent twenty minutes trying to figure out why the test was failing. (The code was correct. I stepped through it a half-dozen times just to make sure I wasn’t imagining things.)

Then, after a little bit of pounding on F1 and then Google, I stumbled upon the answer:

Use CollectionAssert for collections.  Doh!  And, as one of the goals of doing the kata’s is to learn new things, I felt my time was well spent.

Correct code:

[code language=”csharp”] [TestMethod] public void PrimeFactorsOfTwo() { List expected = new List() { 2 }; List actual = Class1.FactorNumber(2); CollectionAssert.AreEqual(expected, actual,”Prime factor of 2 should be 2.”); }[/code]

Written on September 15, 2013