Home > Articles > Programming

📄 Contents

  1. Testing First
  2. How NUnit Works
  3. Writing Your First NUnit Test
  • Print
  • + Share This
From the author of

Writing Your First NUnit Test

I always find thinking of a sample to be the hardest part of writing these tutorials. My NUnit sample is the product of an uninspired mind and an overweight body. Here then is my user story:

The component should provide conversions between pounds and kilos. Conversions should be accurate to two decimal places.

Writing the Sample

Now that you know what to write, go ahead and launch Visual Studio.NET and create a new VB.NET project of type "Class Library", naming it "Person". This will give you a shell class file (class1.vb). Edit class1.vb and add just enough code to define it:

Public Enum ConversionDirection
  KiloToPounds
  PoundsToKilos
End Enum
Public Class Weight
Dim _kilos As Single
   Dim _pounds As Single
  Property Kilos() As Single
    Get
      Return _kilos
    End Get
    Set(ByVal Value As Single)
      _kilos = Value
    End Set
  End Property
  Property Pounds() As Single
    Get
      Return (_pounds)
    End Get
    Set(ByVal Value As Single)
      _pounds = Value
    End Set
  End Property
Sub Convert(ByVal direction As ConversionDirection)
End Sub
End Class

My class has two properties for kilos and pounds. The only method is for conversion. Don't get too hung-up on the "property versus passing parameters to convert" question—we're demonstrating NUnit here. You may have chosen to write even less code, leaving out the setter and getter code in the properties, for example. In my case, I figure that it was so simple that any problems would be caught at compile-time, anyway.

The class has enough definition now, so we'll put it to one side and write a unit test for it.

Writing the Unit Test

To create a NUnit test, you'll need to add a new Class Library project to your existing solution. Go ahead and do this now and name it PersonTest. The last step in preparing your project is to add a reference to the NUnit test framework DLL (nunit.framework.dll); you will find this in the bin folder of your installed directory. I installed NUnit in the default location of c:\Program Files\NUnit V2.0. Open up class1.vb in your test project and add this code (without the line numbers):

1 Imports System
2 Imports NUnit.Framework
3 <TestFixture()> Public Class PersonTests
5   Private oTest As Person.Weight
6   Public Sub New()
7     MyBase.New()
8   End Sub
9   <SetUp()> Public Sub Init()
10     oTest = New Person.Weight()
11   End Sub
12   <Test()>Public Sub TestKiloConversion()
13     System.Console.WriteLine("Running TestKiloConversion()")
14    With oTest
15       .Pounds = 100
16       .Convert(Person.ConversionDirection.PoundsToKilos)
17     End With
18     Assertion.AssertEquals("Failed to convert to Kilos!", "45.45", Format(oTest.Kilos, "#.00"))
19   End Sub
20 End Class

Rebuild your solution, and you're ready to run the test. Before you do that, I want to take a chance to explain how the unit test works. Hitting the tops of the waves we get the following:

  • Lines 1 and 2: I import or make a reference to the base System library and NUnit itself.

  • Line 3: The public method name for the test class: PersonTests denoted by the TestFixture attribute.

  • Line 5: I create a private variable to hold the instance of our Person class.

  • Line 6–8: Standard method constructor for the PersonTests class.

  • Line 9–11: I override the base setup method with my own and create an instance of the Person.Weight object.

  • Line 12–19: I test for the pounds-to-kilograms conversion. Line 20 sees me set the pounds to 100 and then I call the convert method. In line 21, I test the Kilos property and compare to the two-digit string result ("45.45"); the message will be displayed in the NUnit runner if the values are different. And, no, I don't weigh 100 pounds. The test is denoted by the Test() attribute – you can use any name for your test.

I'd like to make it a little more magical, but you'd see through me in no time. That's all there is to writing a unit test with NUnit: Create your object, make it do something, compare the result to what you expected, and make a rude noise if it's wrong. (Well, if not a rude noise, at the very least a curt message to the tester.) The Assert method comes in a number of overloaded flavors: Some take Booleans; others take strings and numeric. The one I'm using takes three parameters:

  • Message string—The message to be displayed if the test fails.

  • Expected result string—the correct result.

  • Actual result string—the result returned by my object.

Ok, now you can run your test. You can do this in three ways:

  • Use the command-line test runner.

  • Use the GUI test runner.

  • Run the project from inside Visual Studio.NET and launch the GUI from there.

Clearly, the last option is the coolest, but you have to run before you can walk. Besides, I want to leave that for my next article-maximum dramatic effect. So, let's run the test from the GUI.

Select your PersonTest binary (PersonTest.dll under the bin folder). Run the test, and you should get the display shown in Figure 3.

Figure 3Figure 3 The example test failing inside NUnit.

Yet another red bar—this is becoming a habit. Considering there is no working code in Person class yet, I'd be concerned if the test passed. One point to note: You can keep the runner window open as you work and simply press "Run" without doing a reload.

Finishing the Test

Go back to the Person class and add the code you need to pass the test. Remember: Your goal is pass the test, not to make perfect code. The listing below is my version of Person the class (hey, don't knock it; at least it works).

1 Public Enum ConversionDirection
2   KiloToPounds
3   PoundsToKilos
4 End Enum
5 Public Class Weight
6   Const CONVERSION_FACTOR As Single = 2.2
7   Dim _kilos As Single
8   Dim _pounds As Single
9   Property Kilos() As Single
10     Get
11       Return _kilos
12     End Get
13     Set(ByVal Value As Single)
14       _kilos = Value
15     End Set
16   End Property
17   Property Pounds() As Single
18     Get
19       Return (_pounds)
20     End Get
21     Set(ByVal Value As Single)
22       _pounds = Value
23     End Set
24   End Property
25  Sub Convert(ByVal direction As ConversionDirection)
26     If direction = ConversionDirection.KiloToPounds Then
27       _pounds = _kilos * CONVERSION_FACTOR
28     Else
29       _kilos = _pounds / CONVERSION_FACTOR
30     End If
31   End Sub
32 End Class

I went back to my Convert method and added some highly complex code to convert to either U.S. or metric weight measurements. I'd like some kind of credit if you use this code in your next killer app. (Naming a child after me would suffice.) Press Run again on the Test Runner and you should see the happy picture shown in Figure 4.

Figure 4Figure 4 The example test passing inside NUnit.

Green At Last, I'm Green At Last

Green at last! Now you have a rock-solid test for the kilo conversion. This means you can dive back into the Person class and refactor to your heart's content.

Refactoring means changing the way your code is written without changing the object's external interfaces. Martin Fowler is the unofficial "keeper of the flame" when it comes to refactoring. Buy his book or visit his site (http://www.refactoring.com).

NOTE

"Refactoring – Improving the design of existing code" by Martin Fowler, Addison Wesley, 1999

Over the last few minutes, you've seen how NUnit supplies you with a simple yet powerful tool for unit testing. NUnit isn't for XP-ers alone! Start using it to test today by doing these steps:

  1. Create your stub class.

  2. Create a test in your NUnit test harness for the class.

  3. Run the test.

  4. Add code to your class and retest until it passes.

Next time around, I'll show you some more tricks with NUnit, including how to run it from Visual Studio.NET.

Now where are those scales...?

  • + Share This
  • 🔖 Save To Your Account