Row Tests or Paramerterized Tests (NUnit)

In a previous post, I discussed Parameter Value Coverage (PVC). One of the easiest ways to add PVC to your test suite is to use Row Tests, sometimes called Parameterized Tests. Row test is the idea of writing a single unit test, but passing many different values in.

Different testing frameworks implement row tests differently.

NUnit has two options. The first implements them inline, with an attribute for each. Here is an example straight from NUnit’s website:

[TestCase(12,3,4)]
[TestCase(12,2,6)]
[TestCase(12,4,3)]
public void DivideTest(int n, int d, int q)
{
    Assert.AreEqual( q, n / d );
}

NUnit also implements a TestCaseSource attribute.

[Test, TestCaseSource("DivideCases")]
public void DivideTest(int n, int d, int q)
{
    Assert.AreEqual( q, n / d );
}

static object[] DivideCases =
{
    new object[] { 12, 3, 4 },
    new object[] { 12, 2, 6 },
    new object[] { 12, 4, 3 }
};

For a single Unit Test, NUnit’s Row tests are far superior. However, for a larger test project, you will see that TestCaseSource with with data sources, scales nicely. Imagine you have 10 test method that each take in the same 10 lines of data. With the TestCase attribute, you would have to write 10 attributes on all 10 test methods–that is 100 lines of attributes alone. Worse these are 10 exact code copies. That breaks the Don’t Repeat Yourself (DRY) principle of coding. With TestCaseSource, you implement the data for the Row tests in a single place and you add one attribute per test method.

Hint: Also, you might find many row test sources can be reused for other tests. Maybe storing them in a single data source repository would be a good idea, so they can be reused. Don’t do it for small tests. Only do it for large test projects that need to scale.

Leave a Reply

How to post code in comments?