Friday 7 January 2011

Row testing with NUnit

In times past there was an extension to NUnit that facilitated row testing (i.e. allowing a test case to be executed multiple times, passing in different values to each run). The extension is no longer required; you can use the [TestCase] attribute instead:

[TestCase("wrongusername", "password")]
[TestCase("username", "wrongpassword")]
[TestCase("worngusername", "wrongpassword")]
public void Validate_WithInvalidUsernameOrPassword_ThrowsException(string username, string password)
    var validator = new SimpleUsernameValidator();
    validator.Validate(username, password);

Note that you can also specify an expected result if the method under test returns a value*:

[TestCase(12,3, Result=4)]
[TestCase(12,2, Result=6)]
[TestCase(12,4, Result=3)]
public int DivideTest(int n, int d)
  return( n / d );

There is also a [TestCaseSource] attribute that can be used in conjunction with [TestCase] to identify a class that can supply test case arguments**:

[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 } 



* TestCaseAttribute (NUnit 2.5)
** TestCaseSourceAttribute (NUnit 2.5)