C# unit testing tip: use the CollectionAssert class to help you work with collections
Posted: (EET/GMT+2)
When writing unit tests for .NET that involve lists or arrays, you can use the CollectionAssert class from MSTest to make the code clearer and get better error messages during test failures.
In C# code, you might utilize the CollectionAssert class like this:
[TestMethod]
public void ProductsAreReturnedInExpectedOrder()
{
var expected = new[] { "A", "B", "C" };
var actual = GetProducts();
CollectionAssert.AreEqual(expected, actual);
}
Here, the AreEqual method tests that the two collections (arrays, lists, ...) are equal in content: the same number of items and the values of the items are the same.
The useful assertion methods don't stop here. For example, you might want to check out these:
CollectionAssert.AreEquivalent: same elements, but in any order.CollectionAssert.AllItemsAreNotNull: quick null check.CollectionAssert.Contains: ensure a certain value exists.
These read naturally and are easier to interpret in test output than looping and asserting manually.