Technology with opinion

Tuesday, September 29, 2009

Practical use for NUNit 2.5's [TestCase]

Since NUnit 2.5, NUnit has supported a concept of Test Cases.  Briefly a test case to NUnit is a test which runs with a different set of parameters and can expect a different set of results.  This has the potential to minimize the amount of code required to write new test methods.

To this point I've been using standard [Test] attributes and since seeing this attribute in the documentation I've been thinking about uses for it.  Now that I've started using [TestCase] I've thought of some other uses for it cutting my test fixtures down to 1/2 or less the size previously.

Below is an simple example of the code without the [TestCase] using the traditional [Test] attribute:


The above code can be trimmed down to one function using the [TestCase] attribute:



The other beautiful thing about [TestCase]s is that it collapses each test case underneath a node which actually looks cleaner:



A couple of notes on the code above.  The compiler (C# here) will not allow you to use object initializers as a parameter to the [TestCase] so you cannot create a test function Validate(object myUser) and do something like below.



This is because the compiler will only allow constants in attributes, however if you really need something like this, NUnit allows a work around. This is documented here.

2 comments:

Matheus Guimaraes said...

hey,
you forgot to link the "documented here" sentence at the bottom when talking about the object initializer workaround, which is exactly what I was looking for. doh!

great blog btw.

ta,
Matt

Andrew Kazyrevich said...

I don't think there's a decent workaround.

The only way is to pass constants in parameters: if your User class has FirstName and LastName properties, you can do

[TestCase("foo", "bar")]
void TestMe(string firstName, string lastName) {
   var user = new User(firstName, lastName);
   ...
}