Purpose of this article:
Till a few months back, I used to be one of those guys who think that testing is the worst thing a software developer could do under the sun. But then, I got introduced to NUnit recently and my perception about testing changed. In this article, I wish to sum up my learning and provide the list of resources that I used.
What is unit testing?
According to Jeff Canna, unit testing ensures that a particular method of a class successfully performs a set of specific tasks. Each test confirms that a method produces the expected output when given a known input.
What is NUnit?
NUnit is an open source framework that facilitates unit testing for all .NET languages.
How do I get NUnit?
Download the appropriate file from here and install it. That’s it!!
Writing NUnit tests
One question that crossed my mind when I was learning NUnit was whether I should create my test project as an executable or as a class library. I finally decided to use a class library because I wouldn’t be running my test project in a stand-alone manner anyway. But, creating a test project as an executable would cause no problems. It’s up to you to decide.
Now, let’s get going. Let us first write the class for which we would write unit test cases. Our class would be called Arithmetica. It would contain four methods to perform the basic arithmetic operations – Add, Subtract, Multiply and Divide.
using System;
namespace Arithmetica
{
public class Arithmetica
{
public int Add(int augend, int addend)
{
return augend + addend;
}
public int Subtract(int minuend, int subtrahend)
{
return minuend - subtrahend;
}
public int Multiply(int firstFactor, int secondFactor)
{
return firstFactor * secondFactor;
}
public int Divide(int dividend, int divisor)
{
return dividend / divisor;
}
}
}
The above code should be placed in a separate project and compiled into a separate assembly. That’s how unit testing is performed. The test cases are not a part of the production code. Implementing unit test within the main assembly not only bloats the actual code, it will also create additional dependencies to NUnit.Framework. Secondly, in a multi-team environment, a separate unit test assembly provides the ease of addition and management. [3]
Now, let’s write the test cases for the Arithmetica class. This would involve the following steps:
1. Create a new project of “Class Library” type (see discussion above) and name it Arithmetica.UnitTests.
2. Add the project containing the Arithmetica class into the solution of Arithmetica.UnitTests.
3. Add reference to nunit.framework.dll. This DLL is located in a directory called bin under the directory where NUnit is installed.
4. Add the following lines in the class in which you are writing the unit test cases:
using System;
using NUnit.Framework;
5. The class which contains the tests must be declared public and decorated with the TestFixture attribute as follows:
namespace Arithmetica
{
[TestFixture]
public class ArithmeticaUnitTests
{
}
}
6. Now, you may want to do setup activities which are performed before executing any test. In our case, we want to create an object of the Arithmetica class. This is done by decorating the method in which you want to perform the setup activities with the TestFixtureSetup attribute as follows:
[TestFixture]
public class ArithmeticaUnitTests
{
private Arithmetica arithmetica;
[TestFixtureSetUp]
public void SetUp()
{
arithmetica = new Arithmetica();
}
}
Note that a TestFixture can have at most one TestFixtureSetup method.
7. You may also want to perform a set of clean up activities after executing all the tests. The method which does this is decorated with the TestFixtureTearDown attribute.
namespace Arithmetica
{
[TestFixture]
public class ArithmeticaUnitTests
{
private Arithmetica arithmetica;
[TestFixtureSetUp]
public void SetUp()
{
arithmetica = new Arithmetica();
}
[TestFixtureTearDown]
public void TearDown()
{
arithmetica = null;
}
}
}
Again, a TestFixture can contain at most one TestFixtureTearDown method. Other setup and teardown attributes for NUnit include SetUp, TearDown, SetUpFixture and TearDownFixture. You may refer NUnit documentation for these.
8. Now, let’s write the test for the Add method. Every test method must be decorated with the Test attribute. You can have as many test methods in a test fixture as you desire.
[Test]
public void TestAdd()
{
int result = arithmetica.Add(2, 3);
Assert.AreEqual(result, 5);
}
Here, the Add method of Arithmetica class is called with the parameters 2 and 3 and the sum is stored in result. Then, we check whether result is equal to 5. You can read more about assertions in NUnit documentation.
9. If you are expecting an exception to be thrown in the test method, you can decorate it with the ExpectedException attribute as follows:
[Test, ExpectedException(typeof(DivideByZeroException))]
public void TestDivide()
{
int result = arithmetica.Divide(2, 0);
}
It must be noted here that the precise type of the exception must be specified in the ExpectedException attribute. Using Exception instead of DivideByZeroException will cause the test to fail.
10. Similarly, you may write the other test cases. Here is the listing of the tests that I wrote:
using System;
using NUnit.Framework;
namespace Arithmetica
{
[TestFixture]
public class ArithmeticaUnitTests
{
private Arithmetica arithmetica;
[TestFixtureSetUp]
public void SetUp()
{
arithmetica = new Arithmetica();
}
[TestFixtureTearDown]
public void TearDown()
{
arithmetica = null;
}
[Test]
public void TestAdd()
{
int result = arithmetica.Add(2, 3);
Assert.AreEqual(result, 5);
}
[Test]
public void TestSubtract()
{
int result = arithmetica.Subtract(3, 2);
Assert.AreEqual(result, 1);
result = arithmetica.Subtract(2, 3);
Assert.AreEqual(result, -1);
}
[Test]
public void TestMultiply()
{
int result = arithmetica.Multiply(2, 3);
Assert.AreEqual(result, 6);
}
[Test, ExpectedException(typeof(DivideByZeroException))]
public void TestDivide()
{
int result = arithmetica.Divide(4, 2);
Assert.AreEqual(result, 2);
result = arithmetica.Divide(2, 0);
}
}
}
After this, build the assembly. Please note that the TestFixtureSetUp, TestFixtureTearDown and Test methods must be defined with the following method signature:
public void MethodName()
Executing the tests
There are two ways for executing the tests:
1. Using nunit-console
I haven’t used this method very much. So, I do not know much about it. To use this method, make sure that the bin directory under the NUnit installation directory is in your PATH environment variable. Go to Start > Run and type cmd to open the command prompt. Then, type the following:
nunit-console <path of the assembly containing the tests>
e.g. nunit-console D:\NUnitTutorial\bin\Release\Arithmetica.UnitTests.dll

For more information on nunit-console, you may refer NUnit documentation.
2. Using nunit-gui
To start nunit-gui, go to Start > Programs > NUnit <version> and select NUnit-Gui. In the NUnit GUI, select File > Open or press Ctrl + O. This would show the Open Project dialog. Browse to the folder which contains the assembly containing your tests and open it.

To execute the tests, simply press the Run button. If the test cases are executed successfully, they would be indicated in green. Failed test cases would be indicated in red. The cause of a failed test can be determined from the Result tab of the Properties window which is displayed by right-clicking on the test and selecting Properties from the context menu. Test cases which are not run would be indicated in yellow.

FAQs
1. NUnit GUI doesn’t load my test fixture. What do I do?
Solution – The test fixture class must be declared public.
2. How can I run NUnit GUI from within Visual Studio.NET?
Solution – This involves the following steps:
(i) From the Tools menu in VS.NET, select External Tools…
(ii) In the dialog box that opens, specify the values for Title, Arguments and Initial Directory fields as shown below:

(iii) The Command field should contain the path of nunit-gui.exe. Click OK.
(iv) Now, you can run nunit-gui by selecting NUnit from the Tools menu in VS.NET.
(v) You can also set a keyboard shortcut for this by setting a keyboard shortcut for Tools.ExternalCommand<command-number>. For more information on setting keyboard shortcuts for VS.NET, see Creating custom keyboard shortcuts in VS.NET.
When I tried running my tests in this manner, I got an error which said:
Arithmetica.ArithmeticaUnitTests (TestFixtureSetUp) : Could not load file or assembly ‘Arithmetica, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null’ or one of its dependencies. The system cannot find the file specified.
The reason for this is that $(TargetPath) refers to the obj\Release directory under the project folder. The referenced assembly (Arithmetica.dll in this case) is not copied to this directory. Hence, I get this error.
One solution could be to copy the referenced assembly manually to this directory. The tests would run fine in that case. But, there is a problem. Everytime I change the referenced assembly, I would have to copy it again. And I’m too lazy to do it this way. So, I prefer to use the nunit-gui outside VS.NET by loading the assembly in one of the folders under the bin folder in the project directory. This way NUnit watches the assemblies for changes and reloads them as soon as they are changed.
3. How do I test private methods?
Solution – Refer [4].
4. How can I debug my NUnit tests?
Solution – Well, all I know is that you can do this. You can use Google to find information on this. As I use the Express Edition of VS.NET, the facility of attaching to an external process is unavailable. So, I couldn’t try this one out. But, I’m sure a lot of good resources are available on the net. So, use Google.
Hope this article helps in your exploration of NUnit.
References:
13 Comments
July 20, 2007 at 5:36 am
Hello,
I have gone through your article and would accept that it is a very good article for beginners. I am currently working at a local company in Pakistan and I am working on Microsoft Dynamcis AX. My team had this idea of integrating Windows Workflow with AX, and for our learning purpose, we started working on an ATM example. Since Workflow’s code was written in C#.Net, I thought about writing the unit tests. Following all the procedure that you have mentioned in your article, I finally ran my test. But the result was shocking. When I loaded the assembly of my project and clicked the Run button, NUnit disappeared. The method been tested performed an account verification by taking an account number as input from the user and matching it with the account number of CustTable in Dynamics AX. I am still confused about what might have caused this. If you have any suggestions, please email me at the address that I’ve provided. Thankyou.
July 26, 2007 at 12:33 pm
[...] Umfangreiches Einsteiger Tutorial für NUnit Tags:.NET, NUnit, Unit Tests, Visual Studio [...]
February 7, 2008 at 6:26 am
Really Good stuff,but look the code below:
public void TestAdd()
{
int result = arithmetica.Add(2, 3);
Assert.AreEqual(result, 5);
}
* The Assert.AreEqual(result,5) , is not a valid statement.
It Should be Assert.AreEqual(5,result);
As the syntax is Assert.AreEqual(Expected,Actual)
*Assert statement should be modified to all the methods.
February 8, 2008 at 3:30 pm
@Prashanthi: Yes, you are right. Thanks for pointing out.
March 15, 2008 at 5:49 pm
Nice tutorial. However, the tutorial implies that your start with a class and start writing tests for that class.
In TDD (test driven development), the goal is to create your test FIRST before any code is written.
This has several advantages. It allows you to design how a system will interact with your class regardless of class implementation.
This makes for more robust design..
Here’s one way it could go.
Come up with a test case
Create your test fixture
Try to compile — it won’t because the class to be tested hasn’t been coded yet.
Add just enough code to get it to compile.
Now NUnit will run but the tests will fail (because of no class implementation).
Implement the part of your class that you are testing until the test passes.
Repeat — Refactor
March 24, 2008 at 1:28 pm
@Bryan: I agree with you. But the point of this article was not to show how to do TDD. In this article, I intended to show how to quickly get started with NUnit.
August 22, 2008 at 3:16 pm
I recently shifted to C# world from Java, and couldn’t get rid of minor problems, but your tutorial helped me setup the environment for future tests perfectly!
November 3, 2008 at 4:51 pm
please tell me the difference between [testsetup] and [testfixturesetup]
December 2, 2008 at 9:12 am
Debugging tests functions and classes can be done by using the Debug->Attach to Process menu option.
Choose Nunit.exe
Put breakpoints wherever you need
December 26, 2008 at 11:46 am
@Kashan: Thanks
@Rani: I guess you are asking the difference between [Setup] and [TestFixtureSetup]. A TestFixtureSetup method is executed once before any of the test methods are executed. A Setup method is executed before the execution of each test method in the test fixture. For more information, you can refer to the NUnit documentation.
@Marc: Thanks. I have mentioned that in the article. But, as I have mentioned in the article, I was unable to do this as I was working with the Express edition of VS.NET 2005 which does not provide this facility.
February 18, 2009 at 11:12 am
hi
i have a doubt what type of input does Nunit require
ie xml,.dll like that
February 18, 2009 at 12:02 pm
any we load xml as a input
March 18, 2009 at 5:50 pm
Great tutorial, thanks!