NUnit TestCase

By Thomas Johnson | March 3, 2009

In my previous post about fitnesse I mentioned that it would be good to have a simple way to specify expected inputs and outputs for a method. I was fairly sure there must be something out there and the latest version of NUnit (Beta version 2.5) offers a great solution.

It allows us to specify parameters for a test method in a way which provides great flexibility. Here you can see how easily we’re able to supply the data for different test cases … the tests run as if you had set up seperate methods for each case.

</code></code></code>

[TestFixture]
public class StringFormatUtilsTest
{
[TestCase("tttt", "")]
[TestCase("", "")]
[TestCase("t3a4b5", "345")]
[TestCase("3&amp;amp;5*", "35")]
[TestCase("123", "123")]
public void StripNonNumeric(string before, string expected)
{
string actual = FormatUtils.StripNonNumeric(before);
Assert.AreEqual(expected, actual);
}
}

You can also use a result parameter to specify an expected return value as follows:

</code></code></code>

[TestFixture]
public class StringFormatUtilsTest
{
[TestCase("tttt", Result="")]
[TestCase("", Result="")]
[TestCase("t3a4b5", Result="345")]
[TestCase("3&amp;amp;5*", Result="35")]
[TestCase("123", Result="123")]
[TestCase("asf", Result="a")]
public string StripNonNumeric(string before)
{
return FormatUtils.StripNonNumeric(before);
}
}

This is great … a clear and concise way to setup multiple test cases for simple tests. If the test setup is more complicated it may not workout out so nicely. I believe other unit test frameworks provide similar functionality so have a look around.

Topics: Coding Style, unit testing |

Comments