Click here to Skip to main content
Click here to Skip to main content

Unit Testing Using NUnit

By , 4 Mar 2013
 

Introduction

In this article, I am giving a basic description about Unit testing and getting started with unit testing framework for .NET, i.e., NUnit. This article can guide from the introduction of unit testing to the tool used for unit testing.

What is Unit Testing?

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

Figure: Unit Testing in Application Development

Unit testing is used to test a small piece of workable code (operational) called units. This encourages developers to modify the 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 the 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 the 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 test are written in .NET supported language, e.g., C#, VC, VB.NET, J#, etc.

NUnit is the derivative of the popular testing framework used by eXtreme Programming(XP). It was created by Philip Craig for .NET. Like for .NET, it is also present 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 the 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 Nunit framework from the above mentioned website.

  1. At first, in the 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:
    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);
                Console.ReadKey();
                int y = helper.Subtract(number1, number2);
                Console.WriteLine("\nThe difference between " + 
    		number1 + " and" + number2 + "  is " + y);
                Console.ReadKey();
            }
        }
    
        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;
            }
        }
  3. 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.
  4. In the newly added project, add a class and name it as TestClass.cs.
  5. In the class file, write the following code:
    [TestFixture]
        public class TestClass
        {
            [TestCase]
            public void AddTest()
            {
                MathsHelper helper = new MathsHelper();
                int result = helper.Add(20, 10);
                Assert.AreEqual(30, result);
            }
    
            [TestCase]
            public void SubtractTest()
            {
                MathsHelper helper = new MathsHelper();
                int result = helper.Subtract(20, 10);
                Assert.AreEqual(10, result);
            }
        }
  6. Now open the test runner(test runner is downloaded from nunit site along with the nunit dlls) and open the project and run it. If the test passes, then the following test screen is displayed:

    Otherwise, the following screen displays:

Important Attributes

1. [SetUp]

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

[SetUp]
public void Xyz()
{
   .
   .
}

The code written in the Xyz method is executed before the test runs and it avoids the call of 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 needs to throw exception in some cases. The cases may be FileNotFoundException and others.

[Test]
[ExpectedException(typeof(MissingFileException))]
public void CheckException()
{
......
......
}

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

4. [TearDown]

This is an attribute thats acts opposite of [SetUp]. It means the code written with this attribute is executed at 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 by its name is the simulation of real object. Mock objects act just as real objects but in a controlled way. Mock object is created to test the behavior of real objects. In unit testing, mock objects are used to scrutinize the performance of real objects. Simply to say mock object is just the imitation of real object. Some important characteristics of mock object are that it is lightweight, easily created, quick, and deterministic and so on.

Stub Object

A stub object is an object which implements an interface of a component. Stub can be configured to return a value as required. Stub objects provide a valid response, but it is 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 the stub object in some ways. They are listed below:

  1. 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 object for every test whilst stubs are often reused between tests.

Conclusion

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

License

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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberVisar Uruqi14-Mar-13 22:21 
its simple and informative
GeneralMy vote of 5membergallysundar11-Mar-13 18:55 
Explained simply with required example to encourage the starter's of Unit Testing..
GeneralMy vote of 5memberSouthmountain5-Mar-13 5:33 
good introduction for beginners.
QuestionMathsHelper object can not be instantiatemembercharakadr23-Jan-13 22:27 
MathsHelper object can not be instantiate.Shows an error
AnswerRe: MathsHelper object can not be instantiatememberankitjc5-Mar-13 9:47 
Reference to the console application needs to be added to the class library project and then, it can be accessed with command like -
 
ConsoleApplication1.MathsHelper helper = new ConsoleApplication1.MathsHelper();

QuestionVery nice introduction for a beginnermemberFourCrate29-Oct-12 9:33 
Very well written, will be needing this for work soon!
GeneralMy vote of 5mvpKanasz Robert28-Sep-12 5:54 
good
QuestionCool NUnitmemberSwinkaran16-Sep-12 20:58 
This is very cool article for beginners. I worked on NUnit 3 years ago,, This article is a good recap.
QuestionResponse..memberamrutakanksha10-Aug-12 0:07 
This Example is really helpful for beginners...!! Smile | :) Smile | :)
QuestionI vote 4memberMember 701715429-Jul-12 12:27 
You are not explicit about which project to load.
And it is not clear that you need to open the DLL of the Test Program.
Otherwise, it is fine.
AT
GeneralMy vote of 5membernikhi _singh28-Mar-12 0:14 
Excellent Article to understand how NUnit Works
QuestionMy 5memberJephunneh Malazarte18-Jan-12 22:35 
I am new to testing procedure. i didn't bother working on that coz i know there's another team to do that until i was assigned to do research regarding this.
 
We are using VS2010 ultimate edition.
Which one is better? the test tool of vs2010 ultimate or the nunit?
Nothing!!!

AnswerRe: My 5memberNeerajan Lamsal21-Feb-12 0:54 
You can use the tools inside VS2010 ultimate as well. It helps to see the code coverage, test results along with many more features. It doesnt mean NUnit is not good.
GeneralRe: My 5memberJephunneh Malazarte21-Feb-12 11:20 
interesting, are you familiar with the libraries being used by microsoft of run the test scripts? i am thinking if may i will be able to create a utility to execute the test scripts automatically without going to vs2010 ultimate. just using the DLLs instead.
Nothing!!!

GeneralMy vote of 4memberjawed.ace13-Apr-11 1:52 
Nicely explain about Nunit!!
but nothing new...
GeneralRe: My vote of 4memberNeerajan Lamsal17-Apr-11 22:10 
Thank you for your vote. In future revisions, there will be something new for sure....
GeneralMy vote of 3memberPerry Bruins12-Apr-11 20:20 
Though telling about NUnit can be helpful, it might be much better to explain about the TDD approach where unittesting plays a keyrole.
GeneralRe: My vote of 3memberNeerajan Lamsal17-Apr-11 22:12 
Thank you for your suggestion. This article is just to give overview. In my next article I'm planning to use TDD alonng with Unit testing in an advanced way. Thanks again..

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130619.1 | Last Updated 5 Mar 2013
Article Copyright 2011 by Neerajan Lamsal
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid