|
This course
- C# and VS.NET 2005 - Automating Unit Testing with NUnit v1.0 - last updated: 08/07/2006 |
NUnit is a unit test harness for use with .NET languages. A test harness allows an application to start at an alternate entry point (rather than a main() method); the harness then controls the flow of execution through a series of test method written by you. You write a test class that contains any required initialization for your application, as well as test methods, and then run the test harness against your compiled executable file. The test harness uses reflection to reach inside the file and test your methods.
Here's how to download and install NUnit on your PC for VS.NET 2005 and the .NET Framework 2.0.
Coding with a good test harness means you can always perform automated regression (unit) testing on your code with the click of a mouse; this helps detect whether future code modifications have broken existing code. Recent "best practice" is to code in this order: 1) write an empty method stub, 2) write a test for the method (this test will fail at this point), and 3) add the real logic to the new method so the test passes.
We are also supposed to automate testing of exceptions. If I know that one of my methods can throw a certain kind of exception, I am supposed to write a test that deliberately causes the exception to occur. Knowing that exception handling is working as expected is as important as knowing how methods perform under normal circumstances.
Here's a
Counter sample project (here's
the counter class code and its
test class) that illustrates the use of NUnit.
Note the three different test methods which test to make sure that an exception
occurred. When NUnit runs this code, the output looks like this:

The list below (obtained from the test harness console output) shows the order
in which the methods in the test class will be called when NUnit controls how
the application runs:
TestFixtureSetUp SetUp Test001IsNull TearDown SetUp Test002IsNotNull TearDown SetUp Test003IncrementOrigValue TearDown SetUp Test004DecrementOrigValue TearDown SetUp Test005AreSame TearDown SetUp Test006AreEqual TearDown SetUp Test007ExceptionThrown TearDown SetUp Test008ExceptionThrown TearDown SetUp Test009ExceptionThrown: System.Exception: messing up now at counter.Counter.ThrowAnException() at counter.TestFixtureSetUpAndTearDownTest.Test009ExceptionThrown() TearDown SetUp Test010ExceptionThrown TearDown TestFixtureTearDown
Visitors: