oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

Unit Testing in .NET Projects

by Jay Flowers

If you didn't know it already, now is a pretty exciting time for unit testing in .NET. Tremendous progress is being made on several fronts: IDE integration, process integration, and new test fixtures. This article will cover unit testing in Visual Studio 2005, including VSTS unit testing, NUnit and MBUnit--the Superman of unit testing.


NUnit is the unit testing framework that has the majority of the market share. It was one of the first unit testing frameworks for the .NET platform. It utilizes attributes to identify what a test is. The TestFixture attribute is used to identify a class that will expose test methods. The Test attribute is used to identify a method that will exercise a test subject. Let's get down to business and look at some code.

First we need something to test:

public class Subject { 
  public Int32 Add(Int32 x, Int32 y)
    return x  + y; 

That Subject class has one method: Add. We will test the Subject class by exercising the Add method with different arguments.

public class tSubject
  public void tAdd()
    Int32 Sum;
    Subject Subject = new Subject();
    Sum = Subject.Add(1,2);
    Assert.AreEqual(3, Sum);

The class tSubject is decorated with the attribute TestFixture, and the method tAdd is decorated with the attribute Test. You can compile this and run it in the NUnit GUI application. It will produce a successful test run.

That is the basics of what NUnit offers. There are attributes to help with setting up and tearing down your test environment: SetUp, SetUpFixture, TearDown, and TearDownFixture. SetUpFixture is run once at the beginning when the fixture is first created; similarly, TearDownFixture is run once after all tests have completed. SetUp and TearDown are run before and after each test.

NUnit tests can be run several different ways: from the GUI application, from the console's application, and from a NAnt task. NUnit has been integrated into Cruise Control .NET as well. In the last product review, you will see how it has been integrated into the VS.NET IDE as well.

NUnit GUI Application
Figure 1. NUnit GUI Application

Visual Studio Hacks

Related Reading

Visual Studio Hacks
Tips & Tools for Turbocharging the IDE
By James Avery

Pages: 1, 2, 3, 4, 5

Next Pagearrow