Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Nunit from Scratch

0.00/5 (No votes)
6 Jan 2017 1  
In this article we will see one of the most important unit testing framework in DotNet.

Introduction

Every successful software development is following a lifecycle known as SDLC(Software Development Life Cycle).As per Wikipedia

"SDLC is a process followed for a software project, within a software organization. It consists of a detailed plan describing how to develop, maintain, replace and alter or enhance specific software. The life cycle defines a methodology for improving the quality of software and the overall development process."

(An Image from Wiki)

As we are a developer we normally understand the requirements and write the code.Apart from those we also some time involved in Software Testing.

Software testing is a process of executing a program or application with the intent of finding the software bugs.

It can also be stated as the process of validating and verifying that a software program or application or product.

I have googled and tried to find out what kind of testing a developer can do.I got lot  of solution from Internet the best one i found is here.
So mainly a developer must have knowledge of Unit Testing. 

what is unit Testing?

let as try to find the exact defination of Unit first.

UNIT:-In this IT world a unit refers to simply a smallest piece of code which takes an input does certain opperation and gives an output.

And testing this small piece of code is called Unit Testing.

A lot of unit test framework are available for .Net now a day,if we check in Visual studio we have MSTest from Microsoft integrated in Visual Studio.

Some 3rd party framework are like-

NUnit

MbUnit

Out of all these Nunit is the most  used testing Framework.

What Is NUnit?

NUnit is a unit-testing framework for all .Net languages. 

NUnit is Open Source software and NUnit 3.0 is released under the MIT license.  This framework is very easy to work and has user friendly attributes for working.

You can check the details of Nunit from here. 

If you want to learn what are the main diffrence between MsTest and Nunit i recomanded you to check the following Link. 

You can also check several other links that are available in internet.I did a small inspection in internet and found the following result in using different Testing framework.As per Slant website this is what most peoples recommendation on using different unit Testing framework. 

This image is from Slant.


To work with Nunit Let setup a simple console application as follow.

write the following class in this project.

public class EmployeeDetails  
    {  
        public int id { get; set; }  
        public string Name { get; set; }  
        public double salary { get; set; }  
        public string Geneder { get; set; }  
    }  
}  

Now in the class programme write some conditions which need to be tested.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
  
namespace DemoProject  
{  
   public class Program  
    {  
         
        public string Login(string UserId,string Password)  
        {  
            if(string.IsNullOrEmpty(UserId) || string.IsNullOrEmpty(Password))  
            {  
                return "Userid or password could not be Empty.";  
            }  
            else  
            {  
                if(UserId=="Admin" && Password=="Admin")  
                {  
                    return "Welcome Admin.";  
                }  
                return "Incorrect UserId or Password.";  
  
            }  
  
        }  
        public List<EmployeeDetails> AllUsers()  
        {  
            List<EmployeeDetails> li = new List<EmployeeDetails>();  
            li.Add(new EmployeeDetails { id = 100, Name = "Bharat", Geneder = "male", salary = 40000 });  
            li.Add(new EmployeeDetails { id = 101, Name = "sunita", Geneder = "Female", salary = 50000 });  
            li.Add(new EmployeeDetails { id = 103, Name = "Karan", Geneder = "male", salary = 40000 });  
            li.Add(new EmployeeDetails { id = 104, Name = "Jeetu", Geneder = "male", salary = 23000 });  
            li.Add(new EmployeeDetails { id = 105, Name = "Manasi", Geneder = "Female", salary = 80000 });  
            li.Add(new EmployeeDetails { id = 106, Name = "Ranjit", Geneder = "male", salary = 670000 });  
            return li;  
  
        }  
        public List<EmployeeDetails> getDetails(int id)  
        {  
            List<EmployeeDetails> li1 = new List<EmployeeDetails>();  
            Program p = new Program();  
            var li = p.getUserDetails();  
            foreach (var x in li)  
            {  
                if(x.id==id)  
                {  
                    li1.Add(x);  
                }  
            }  
            return li1;  
  
        }  
        static void Main(string[] args)  
        {  
              
  
        }  
    }  
}  

So here i have written 3 methods or we can say some requirements which we want to test by using Unit Test.
so please add a new project(Class Library Type) in the Solution Explorer as follow.

The Nunit framework does not require any specific project type, but most of the time people will add a class library to separate their code from their unittests. You need to reference the nunit.framework.dll yourself. But if you use nuget this will be done for you automatic while installing NUnit.

So for using Nunit we need to go for Nuget Package Manager and download it.

After downloading we will find the nunit referances in our project.

 

 Now after installing the Nunit we need one more dll that need to be installed in the project.

 

NUnit Test Adapter for Visual Studio:

The NUnit Test Adapter allows you to run NUnit tests inside Visual Studio. 

NOTE:-If you will not add this component in your project you will not able to find your tests in test Explorer .

NOTE:-You need to install both the Library in the project where you are writing the test methods only.

Before start writing any test case lets go get aware of all the components we are using in Nunit. If you will check the Nunit site you will get all the attributes and other components details there.
https://www.nunit.org/.

Now our next work is to add the Demo Project dll in DemoProjectTest Referances.


Now it will add the following dll to the references.

So here is the  Test cases i have written to test our Requirements.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
using NUnit.Framework;  
using DemoProject;  
  
namespace DemoProjectTest  
{  
    [TestFixture]  
    public class DemoTests  
    {  
        List<EmployeeDetails> li;  
        [Test]  
         
        public void Checkdetails()  
        {  
            Program pobj = new Program();  
            li = pobj.AllUsers();  
            foreach(var x in li)  
            {  
                Assert.IsNotNull(x.id);  
                Assert.IsNotNull(x.Name);  
                Assert.IsNotNull(x.salary);  
                Assert.IsNotNull(x.Geneder);  
                  
            }  
        }  
        [Test]  
        public void TestLogin()  
        {  
            Program pobj = new Program();  
            string x = pobj.Login("Ajit", "1234");  
            string y = pobj.Login("", "");  
            string z = pobj.Login("Admin", "Admin");  
            Assert.AreEqual("Userid or password could not be Empty.",y);  
            Assert.AreEqual("Incorrect UserId or Password.", x);  
            Assert.AreEqual("Welcome Admin.", z);  
  
        }  
        [Test]  
        public void getuserdetails()  
        {  
            Program pobj = new Program();  
           var p= pobj.getDetails(100);  
            foreach(var x in p)  
            {  
                Assert.AreEqual(x.id, 100);  
                Assert.AreEqual(x.Name,"Bharat");  
  
            }  
              
  
        }  
  
  
    }  
  
}  

TestFixture:-The class that is to be test using Nunit should be decorated with TextFixture.

Test:-This attribute identify the method to be tested.If we will not write this attribute then we cant be able to identify the test in Testexplorer.

 We have a Assert class with following methods for validating diffrent condition in the TestFixture.

Each methods have diffrent diffrent functions.To know about this please check the Nunit Home Page.
Now Lets check our test.Go to the Visual studio Test Explorer.


Here is our Test Explorer where we see all our TestCases.

Now from here if we run a test indiviusally just Right click on it and Run the Test

so in this way we can run the tests.
If the test Run successfully it will show the following tick mark.

Beside these attribute we have some more  attributes like-
 

1)SetUp:-This attribute is used when you want to execute a piece of code in each test case.

It identifies a method to be executed each time before a TestMethod/Test is executed.
Lets check this with an example.Here i have created a new project for testing.Here i have created four test methods.

Now lets check the methods.

So here i have the methods where we have used setUp attribute.Lets try to debugg and check SubMethod.For debugging just Right Click and Debug selected Test.


Now if we notice the sequence it will go to the Addmethod first like these.

Thus the method where the setup attribute is written will be executed first before any test method. 

 

2)TearDown:-After completely executing each test if you want to execute a piece of code then you have to write this code under TearDown attribute.

So lets check this  again.So we have set breakpoints to check the sequence of execution.

 

If we check the sequence of execution the method that used TearDown attribute will be executed last after execution of the Test case.

 

Points To Remember

Note:-If there are 2 SetUp classes are there the class that was written first will be executed first and then after the class that is written next to it will execute.(Top to button approach).

Similarly In tear down the order is reversed it will follow button to Top approach.

Referances

So in this way we can test our requirements using Nunit Testing.I will explain about  all the remaining attributes in my next article.Hope this article will help you to learn the basic concepts of Nunit.

http://nunit.org

https://www.slant.co/topics/543/~unit-testing-frameworks-for-net 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here