Collection Asserts with NUnit

After the previous tip for using test cases from previous week, there is another one. When testing, and I hope you are testing, you have to often deal with collection asserts.

[Test]
public void ReturnsForX()
{
    var x = new X();

    IList<int> results = Class.TestMethod(x);
    
    Assert.AreEqual(5, results.Length);
    Assert.AreEqual(1, results[0]);
    Assert.AreEqual(2, results[1]);
    Assert.AreEqual(3, results[2]);
    Assert.AreEqual(4, results[3]);
    Assert.AreEqual(5, results[4]); 
}

A little boring and yet unreadable code, don’t you think? There are some options to make it better, but I’ve seen this style quiet often in the code bases. Fortunately for us, NUnit comes with CollectionAssert – a class that handles sequence comparison very well.

[Test]
public void ReturnsForX()
{
    var x = new X();
    var expected = new [] { 1, 2, 3, 4, 5 };

    IList<int> results = Class.TestMethod(x);
    
    CollectionAssert.AreEqual(expected, results);
}

That’s all you have to do and there is even more. Maybe you are dealing with unordered collections and that the method AreEquivalent comes to place.

[Test]
public void ReturnsForX()
{
    var x = new X();
    var expected = new [] { 1, 5, 2, 4, 3 };

    IList<int> result = Class.TestMethod(x);
    
    CollectionAssert.AreEquivalent(expected, results);
}

I recommend you to check this helper class and decide for yourself which methods can improve your tests.


Would you like to get the most interesting content about C# every Monday?
Sign up to C# Digest and stay up to date!