File this one under "old features I'm only now learning about." It seems NUnit has had a RowTest extension built in since March of 08...
For example, let's say I have a method called Add that adds two integers and returns the result. (The internals of that method are highly complex and I won't go into details here.) If you wanted to test two positive integers, a unit test would look like this:
[Test]
public void AddTwoPositiveNumbers()
{
Assert.AreEqual(2 + 3, Add(2, 3),
"Add returned incorrect result");
}
To test two negative integers you would historically create a second, nearly identical unit test:
[Test]
public void AddTwoNegativeNumbers()
{
Assert.AreEqual(-1 + -4, Add(-1, -4),
"Add returned incorrect result");
}
For reference, the two tests will appear under the class name when viewed through the NUnit GUI.
Now, these don't seem too bad, but what happens if you needs lots of nearly-identical tests? Or these tests need to perform additional steps? Copy/paste is a bad programming practice, even for unit tests. Fortunately, Nunit provides an extension (under the NUnit.Framework.Extensions namespace not surprisingly) that makes life much easier - the RowTest.
To use, create a single test method with parameters for the varying test data. Decorate the method with a RowTest attribute, and one Row attribute for each test case. The above unit tests can now be replaced by:
[RowTest]
[Row(2, 3)]
[Row(-1, -4)]
public void AddTwoNumbers(int x, int y)
{
Assert.AreEqual(x + y, Add(x, y),
"Add returned incorrect result");
}
Changes to the test set becomes much easier, as does adding new tests. In the GUI, you'll see each Row split out as an individual test beneath the generic test:
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.