Click here to Skip to main content
15,116,653 members
Articles / DevOps / Testing
Posted 7 Apr 2011

Tagged as


125 bookmarked

Unit Testing Using NUnit

Rate me:
Please Sign up or sign in to vote.
4.83/5 (64 votes)
25 Jul 2013GPL35 min read
Unit Testing using NUnit.


In this article, I am giving a basic description about Unit testing and getting started with a unit testing framework for .NET, NUnit. This article is an introduction to unit testing and explains a tool used for unit testing.

What is Unit Testing?

Unit testing is a kind of testing done at the developer side. It is used to test methods, properties, classes, and assemblies. Unit testing is not testing done by the quality assurance department. To know where unit testing fits into development, look at the following image:

Image 1

Figure: Unit Testing in Application Development

Unit testing is used to test a small piece of workable code (operational) called unit. This encourages developers to modify code without immediate concerns about how such changes might affect the functioning of other units or the program as a whole. Unit testing can be time consuming and tedious, but should be done thoroughly with patience.

What is NUnit?

NUnit is a unit testing framework for performing unit testing based on the .NET platform. It is a widely used tool for unit testing and is preferred by many developers today. NUnit is free to use. NUnit does not create any test scripts by itself. You have to write test scripts by yourself, but NUnit allows you to use its tools and classes to make unit testing easier. The points to be remembered about NUnit are listed below:

  1. NUnit is not an automated GUI testing tool.
  2. It is not a scripting language, all tests are written in .NET supported languages, e.g., C#, VC, VB.NET, J#, etc.

NUnit is a derivative of the popular testing framework used by eXtreme Programming (XP). It was created by Philip Craig for .NET. It is also available in the name of jUnit for Java code testing.

NUnit works by providing a class framework and a test runner application. They can be downloaded from here. The class framework allows to write test cases based on the application. The test is run using the test runner application downloaded from the above link.

Steps for Using NUnit

First, what one needs to do is download the recent version of the NUnit framework from the above mentioned website.

  1. In development studio, create a new project. In my case, I have created a console application.
  2. In the program.cs file, write the following code:
  3. C#
    class Program
        static void Main(string[] args)
            Console.WriteLine("Enter two numbers\n");
            int number1;
            int number2;
            number1 = int.Parse(Console.ReadLine());
            number2 = int.Parse(Console.ReadLine());
            MathsHelper helper = new MathsHelper();
            int x = helper.Add(number1, number2);
            Console.WriteLine("\nThe sum of " + number1 + 
                " and " + number2 + " is " + x);
            int y = helper.Subtract(number1, number2);
            Console.WriteLine("\nThe difference between " + 
                  number1 + " and" + number2 + "  is " + y);
    public class MathsHelper
        public MathsHelper() { }
        public int Add(int a, int b)
            int x = a + b;
            return x;
        public int Subtract(int a, int b)
            int x = a - b;
            return x;
  4. Then to the solution of the project, add a new class library project and name it followed by “.Test” (it is the naming convention used for unit testing). Import the downloaded DLL files into the project and follow the steps given below.
  5. In the newly added project, add a class and name it TestClass.cs.
  6. In the class file, write the following code:
  7. C#
    public class TestClass
        public void AddTest()
            MathsHelper helper = new MathsHelper();
            int result = helper.Add(20, 10);
            Assert.AreEqual(30, result);
        public void SubtractTest()
            MathsHelper helper = new MathsHelper();
            int result = helper.Subtract(20, 10);
            Assert.AreEqual(10, result);
  8. Now open the test runner (test runner is downloaded from the NUnit site along with the NUnit DLLs). In the NUnit API, click File > Open project. A file open dialog appears. Give the path of the NUunit test project DLL. Now run the test. If the test passes, then the following test screen is displayed:
  9. Image 2

    Otherwise, the following screen displays:

    Image 3

Important Attributes

1. [SetUp]

SetUp is generally used for initialization purposes. Any code that must be initialized or set prior to executing a test is put in functions marked with this attribute. As a consequence, it avoids the problem of code repetition in each test.

public void Xyz()

The code written in the Xyz method is executed before the test runs and it avoids the call of the code inside this method.

2. [Ignore]

This is the attribute which is used for the code that needs to be bypassed.

3. [ExpectedException]

This attribute is used to test methods that need to throw an exception in some cases. The cases may be FileNotFoundException and others.

public void CheckException()

The code shouldn't have any Assert statement. On passing the test, the code should throw an exception, otherwise an exception is not thrown.

4. [TearDown]

This is an attribute that acts the opposite of [SetUp]. It means the code written with this attribute is executed last (after passing other lines of code). So, inside this closing is generally done, i.e., closing of file system, database connection, etc.

Mock Objects

A mock object is a simulation of a real object. Mock objects act just as real objects but in a controlled way. A mock object is created to test the behavior of a real object. In unit testing, mock objects are used to scrutinize the performance of real objects. Simply said, a mock object is just the imitation of a real object. Some important characteristics of mock objects are that they are lightweight, easily created, quick and deterministic, and so on.

Stub Object

A stub object is an object which implements an interface of a component. A stub can be configured to return a value as required. Stub objects provide a valid response, but it is of static nature meaning that no matter what input is passed in, we always get the same response.

Mock Object vs. Stub Object

Mock objects vary from stub objects in some ways. They are listed below:

  1. The first distinct factor is that mock objects test themselves, i.e., they check if they are called at the proper time in the proper manner by the object being tested. Stubs generally just return stubbed data, which can be configured to change depending on how they are called.
  2. Secondly, mock objects are generally lightweight relative to stubs with different instances set for mock objects for every test whilst stubs are often reused between tests.


These are the basic steps for using the NUnit framework for unit testing. Happy coding.


This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


About the Author

Neerajan Lamsal
Software Developer
Nepal Nepal
I am a software developer with knowledge of C, C++, PHP, MySQL, C#.Net, ADO.Net, MSSQL Server, Crystal Reports, Asp.Net, Oracle, Asp.Net MVP, MVC, jQuery, javascript, WebService, WCF, Entity Framework and so on. I love to play on New Technologies.

Comments and Discussions

Questiontest runner link Pin
Member 108845258-Mar-17 5:19
MemberMember 108845258-Mar-17 5:19 
AnswerRe: test runner link Pin
Neerajan Lamsal28-Feb-18 6:13
MemberNeerajan Lamsal28-Feb-18 6:13 
QuestionWhich Nunit Version we need to download? Pin
aakriti171114-Dec-15 0:15
Memberaakriti171114-Dec-15 0:15 
AnswerRe: Which Nunit Version we need to download? Pin
Neerajan Lamsal28-Feb-18 6:15
MemberNeerajan Lamsal28-Feb-18 6:15 
PraiseVery helpfull - thanks Pin
Member 856433730-Nov-15 3:54
MemberMember 856433730-Nov-15 3:54 
QuestionWhere to get a GUI test runner Pin
vikas chaudhary20-Apr-15 21:39
Membervikas chaudhary20-Apr-15 21:39 
AnswerRe: Where to get a GUI test runner Pin
Ryan_S25-Sep-15 5:36
MemberRyan_S25-Sep-15 5:36 
QuestionNUnit working Pin
Gauri Chodanker23-Dec-14 21:18
MemberGauri Chodanker23-Dec-14 21:18 
AnswerRe: NUnit working Pin
Neerajan Lamsal28-Feb-15 7:43
MemberNeerajan Lamsal28-Feb-15 7:43 
Questiontype or namespace name could not be found Pin
Member 1107198111-Nov-14 23:41
MemberMember 1107198111-Nov-14 23:41 
AnswerRe: type or namespace name could not be found Pin
Neerajan Lamsal28-Feb-15 13:51
MemberNeerajan Lamsal28-Feb-15 13:51 
Questionnunit.framework is not required in NUnit_Application project Pin
sreelal28-May-14 3:58
Membersreelal28-May-14 3:58 
AnswerRe: nunit.framework is not required in NUnit_Application project Pin
Neerajan Lamsal28-Feb-15 13:54
MemberNeerajan Lamsal28-Feb-15 13:54 
GeneralMy vote of 5 Pin
DK0919-Mar-14 2:38
MemberDK0919-Mar-14 2:38 
Well done.
GeneralRe: My vote of 5 Pin
Neerajan Lamsal28-Feb-15 13:55
MemberNeerajan Lamsal28-Feb-15 13:55 
QuestionMy Vote of 4 Pin
WarLock00711-Mar-14 2:37
MemberWarLock00711-Mar-14 2:37 
SuggestionPlease add complete test class code Pin
Narendra_LC7-Feb-14 1:14
MemberNarendra_LC7-Feb-14 1:14 
QuestionGreat and Fantastic Example. Ignored TestCases for NUnit 2.4 Pin
Mugwump32725-Jul-13 7:23
MemberMugwump32725-Jul-13 7:23 
GeneralMy vote of 5 Pin
Visar Uruqi14-Mar-13 23:21
MemberVisar Uruqi14-Mar-13 23:21 
GeneralRe: My vote of 5 Pin
Neerajan Lamsal25-Jul-13 1:24
MemberNeerajan Lamsal25-Jul-13 1:24 
GeneralMy vote of 5 Pin
gallysundar11-Mar-13 19:55
Membergallysundar11-Mar-13 19:55 
GeneralRe: My vote of 5 Pin
Neerajan Lamsal25-Jul-13 1:24
MemberNeerajan Lamsal25-Jul-13 1:24 
GeneralMy vote of 5 Pin
Southmountain5-Mar-13 6:33
MemberSouthmountain5-Mar-13 6:33 
GeneralRe: My vote of 5 Pin
Neerajan Lamsal25-Jul-13 1:25
MemberNeerajan Lamsal25-Jul-13 1:25 
QuestionMathsHelper object can not be instantiate Pin
charakadr23-Jan-13 23:27
Membercharakadr23-Jan-13 23:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.