Mathias Brandewinder on .NET, F#, VSTO and Excel development, and quantitative analysis / machine learning.
by Mathias 17. May 2009 02:25

Another nice improvement coming with NUnit 2.5 is the mechanism for data-driven tests. NUnit 2.4.7 included an extension by andreas schlapsi which permitted to write row tests, using the [TestRow] attribute.

NUnit 2.5 eases the process with the [TestCase] attribute. Unlike [TestRow], the [TestCase] attribute is available within the NUnit.Framework namespace, and doesn’t require including additional references.

Why do Data-driven tests matter? They are not technically necessary: you can write the same tests as easily using the standard [Test] attribute. However, it comes handy when you are testing a feature where you want to verify the behavior for multiple combinations of input values. Using “classic” unit tests, you will end up duplicating test code, and you will have to find different name for tests method which are in essence the same test.

Using [TestCase] instead, here is how it looks. Suppose your class MyClass has a method “Divide” like this one:

public class MyClass
{
    public double Divide(double numerator, double denominator)
    {
        if (denominator == 0)
        {
            throw new DivideByZeroException("Cannot divide by zero."); 
        }
        return numerator / denominator;
    }
}

One way to test that feature would be with a test like that one:

[TestCase(2.5d, 2d, Result=1.25d)]
[TestCase(-2.5d, 1d, Result = -2.5d)]
public double ValidateDivision(double numerator, double denominator)
{
    var myClass = new MyClass();
    return myClass.Divide(numerator,denominator);
}

More...

Comments

Comment RSS