Tag: nunit

Making NUnit parameterized tests less verbose

If you are a heavy user of NUnit parameterized tests, especially ones driven by TestCaseSourceAttribute, you might sometimes wish for a less verbose test data definition. Consider the following (contrived) example:

private static readonly object[] _additionCases =
{
  new object[] { new DateTime(2017, 06, 06, 21, 16, 14), new TimeSpan(0, 0, 13), new DateTime(2017, 06, 06, 21, 16, 27) },
  new object[] { new DateTime(2017, 06, 06, 21, 16, 14), new TimeSpan(0, 0, 56), new DateTime(2017, 06, 06, 21, 17, 10) },
  new object[] { new DateTime(2017, 06, 06, 21, 16, 14), new TimeSpan(0, 59, 56), new DateTime(2017, 06, 06, 22, 16, 10) }
};

[Test, TestCaseSource(nameof(_additionCases))]
public void Addition(DateTime source, TimeSpan difference, DateTime expected)
{
  Assert.That(source.Add(difference), Is.EqualTo(expected));
}

Clearly, repeated new object[] type declarations steal some line width and don’t make understanding of the test data any easier.

However, there is a solution. While NUnit documentation illustrates TestCaseSourceAttribute with array of arrays, it also informs that any IEnumerable will do. Therefore, we can create our own class for that, and also use a succinct initialization trick for collections implementing Add method:

public class TestCaseList: List<object[]>
{
  public new void Add(params object[] data)
  {
    base.Add(data);
  }
}

With a help of this small class, the original test can be written as follows:

private static readonly TestCaseList _additionCases = new TestCaseList
{
  { new DateTime(2017, 06, 06, 21, 16, 14), new TimeSpan(0, 0, 13), new DateTime(2017, 06, 06, 21, 16, 27) },
  { new DateTime(2017, 06, 06, 21, 16, 14), new TimeSpan(0, 0, 56), new DateTime(2017, 06, 06, 21, 17, 10) },
  { new DateTime(2017, 06, 06, 21, 16, 14), new TimeSpan(0, 59, 56), new DateTime(2017, 06, 06, 22, 16, 10) }
};

[Test, TestCaseSource(nameof(_additionCases))]
public void Addition(DateTime source, TimeSpan difference, DateTime expected)
{
  Assert.That(source.Add(difference), Is.EqualTo(expected));
}

That looks definitely better!

Advertisements