NUnit With C#


The latest version 3.2.1 of Nunit.exe can download from:

The installation process barely requires a few minutes once the executable is downloaded. The NUnit graphical user interface looks as in the following after the installation process has completed.


Figure 1.1 NUnit GUI

After launching the NUnit.exe GUI, it is time to open a project in the form of a DLL or EXE file on which all the unit test cases executed. For that purpose go to the File menu and select Open Project, now choose the Test case DLL or EXE file and Unit Test case process is ready to execute as described in the following.

NOTE: NUnit Software will only open the assembly (DLL or EXE) that are developed under Test Driven project Methodology.


Figure 1.2 NUnit Project Loading

NUnit Testing Framework

NUnit is a unit-testing framework for .NET applications in which the entire application is isolated into diverse modules. Each module is tested independently to ensure that the objective is met. The NUnit Framework caters a range of attributes that are used during unit tests. They are used to define Test -Fixtures, Test methods, ExpectedException and Ignore methods.

TextFixture Attribute

The TestFixture attribute is an indication that a class contains test methods. When you mention this attribute to a class in your project, the Test Runner application will scan it for test methods. The following code illustrates the usage of this attribute as in the following:

  1. using System;
  2. using NUnit.Framework;   
  3. using System.Text;  
  4. namespace UNitTesting
  5. {
  6.     [TestFixture]  
    public class Program  
  9. }
  10. }  
Test Attribute

The Test attribute indicates that a method within a test fixture should be run by the Test Runner application. The method must be public, return void, and will not be run when the Test Fixture is run. The following code depicts the use of this attribute as in the following:

  1. [TestFixture]  
  2. public class Program  
  3. {  
  4.     [Test]  
  5.     public void Test()  
  6.     {  
  7.        ...  
  8.     }  
  9. }  
Assert Class

the Assert class is used to confirm whether the test cases is producing the expected result or not using its auxiliary methods such as AreEqual() or AreNotEqual().

ExpectedException Attribute

You could fortify your code to handle various exceptions by using try...Catch blocks. But sometimes you have some circumstances where you actually want to ensure that an exception occurs. To overcome such a problem you should use the ExpectedException attribute as in the following;
  1. [TestFixture]  
  2. public class Program  
  3. {  
  4.     [Test]  
  5.     [ExpectedException(typeof(DivideByZeroException))]  
  6.     public void Test()  
  7.     {  
  8.         int i=10,j=0,x;  
  9.         x = i / j;  
  10.     }  
  11. }  
In the previous code, we are intentionally committing a divide by zero exception that is to be detected during the NUnit Test execution.

Ignore Attribute

The Ignore attribute is required to indicate that a test should not be run on a particular method. Use the Ignore attribute as in the following:
  1. [TestFixture]  
  2. public class Program  
  3. {  
  4.     [Test]  
  5.     [Ignore("This method is skipping")]  
  6.     public void Test()  
  7.     {  
  8.          ...  
  9.     }  
  10. }  
Simple Business Logic Project

In the following, we are implementing Discounts on specific sales made my customers such as 5% discount on purchases of $1000 to $1999, 10% on $2000 to $4999 and so on. Such a discount will be deducted automatically in the final payment based on some implicit calculation stated in the business logic.
  1. Create a C# .Net Class Library project called UnitTest to produce a Dll.

  2. Rename the class1 to UtilityLib and use the following business logic:

    1. using System;  
    2. using System.Text;  
    4. namespace UnitTest  
    5. {  
    6.     public classUtilityLib  
    7.     {  
    8.         public double calculateDiscount(double SalesAmnt)  
    9.         {  
    10.             double DiscountPrice = 0.0;  
    12.             if (SalesAmnt == 0 || SalesAmnt < 0)  
    13.             {  
    14.                 thrownew ArgumentException(" Sales Amount should not be 'Zero/Negative'");  
    15.             }  
    16.             else if (SalesAmnt >= 1000 && SalesAmnt < 2000)  
    17.             {  
    18.                 // 5% Discount  
    19.                 DiscountPrice = SalesAmnt - (SalesAmnt * 0.05);  
    20.             }  
    21.             else if (SalesAmnt >= 2000 && SalesAmnt < 5000)  
    22.             {  
    23.                 // 10% Discount  
    24.                 DiscountPrice = SalesAmnt - (SalesAmnt * 0.1);  
    25.             }  
    27.             else if (SalesAmnt >= 5000 && SalesAmnt < 20000)  
    28.             {  
    29.                 // 50% Discount  
    30.                 DiscountPrice = SalesAmnt - (SalesAmnt * 0.5);  
    31.             }  
    32.             else  
    33.             {  
    34.                 // No Discount  
    35.                 DiscountPrice = SalesAmnt - 0.0;  
    36.             }  
    38.             return DiscountPrice;  
    39.         }  
    40.     }  
    41. }  

  3. Now build the project and note that the UnitTest.dll file is created in the solution Bin/Debug folder that would be referenced in the Unit Test project later.

Test-Driven Project Development

There are a few steps to execute the unit test using NUnit as follows;

  1. Create another C# .Net Class Library project called UtilityLibtesting.

  2. Then add a reference for the UnitTest.dll and NUnit framework DLL files that reside in the "\Program Files\NUnit 2.6.2\bin\framework\nunit.framework.dll" directory.


    Figure 1.3 Add references of NUnit framework and UnitTest.dll

  3. Now add the namespace definition to the class library file as follows:

    using NUnit.Framework;
    using UnitTest;

  4. Now rename the class1.cs to TestCase.cs with TextFixture attribute.

  5. It is time to write test case methods to verify whether the business logic stated in the DLL file is producing the expected result or not.

  6. So we write another independent method for each corresponding function given in the DLL file with the [test] attribute and we also use the assert class to AreEqual() method in order to confirm the desired result. The AreEqual() method would take two arguments; the first is the expected result and the second specific method with an argument defined in the business logic class.

    1. // Test Case#1: Sales Amount is Greater or Equal than 1000 : Verification  
    2. [Test]   
    3. public void OneThousand_G_E()  
    4. {  
    5.     UtilityLib obj =new UtilityLib();  
    6.     Assert.AreEqual(950,obj.calculateDiscount(1000));  
    7. }
  7. We also put the condition for actual test cases by using the assert class AreNotEqual() method in which we pass any value as the first argument as in the following:

    1. //______________Test for Actual Results____________  
    2. // Test Case#6: Sales Amount is not producing expected Result : Verification  
    3. [Test]   
    4. public void OneThousand()  
    5. {  
    6.     UtilityLib obj =new UtilityLib();  
    7.     Assert.AreNotEqual(930, obj.calculateDiscount(1000));  
    8. }
  8. Thereafter we specify the rest of the code for each condition as in the following:

    1. using System;  
    2. using NUnit.Framework;    
    3. using UnitTest;  
    5. namespace UtilityLibTesting  
    6. {  
    7.     [TestFixture]  
    8.     public classTestCase  
    9.     {  
    10.         //__________Test for Expected Results__________  
    12.         // Test Case#1: Sales Amount is Greater or Equal than 1000 : Verification  
    13.         [Test]   
    14.         public void OneThousand_G_E()  
    15.         {  
    16.             UtilityLib obj =new UtilityLib();  
    18.             Assert.AreEqual(950,obj.calculateDiscount(1000));  
    19.         }  
    21.         // Test Case#2: Sales Amount is Greater or Equal than 2000 : Verification  
    22.         [Test]   
    23.         public void TwoThousand_G_E()  
    24.         {  
    25.             UtilityLib obj =new UtilityLib();  
    27.             Assert.AreEqual(1800, obj.calculateDiscount(2000));  
    28.         }  
    30.         // Test Case#3: Sales Amount is Greater or Equal than 5000 : Verification  
    31.         [Test]   
    32.         public void FiveThousand_G_E()  
    33.         {  
    34.             UtilityLib obj =new UtilityLib();  
    36.             Assert.AreEqual(2500, obj.calculateDiscount(5000));  
    37.         }  
    39.         // Test Case#4: Sales Amount is 0 : Verification  
    40.         [Test]   
    41.         public void ZeroAmount()  
    42.         {  
    43.             UtilityLib obj =new UtilityLib();  
    44.             try  
    45.             {  
    46.                 obj.calculateDiscount(0);  
    47.             }  
    48.             catch (Exception e) { }  
    50.         }  
    52.         // Test Case#5: Sales Amount is below 1000 : Verification  
    53.         [Test]  
    54.         public void OneThousand_Below()  
    55.         {  
    56.             UtilityLib obj =new UtilityLib();  
    57.             Assert.AreEqual(999, obj.calculateDiscount(999));  
    58.         }  
    60.         //__________Test for Actual Results__________  
    61.         // Test Case#6: Sales Amount is not producing expected Result : Verification  
    62.         [Test]   
    63.         public void OneThousand()  
    64.         {  
    65.             UtilityLib obj =new UtilityLib();  
    67.             Assert.AreNotEqual(930, obj.calculateDiscount(1000));  
    68.         }  
    70.         // Test Case#7: Sales Amount is not producing expected Result : Verification  
    71.         [Test]   
    72.         public void TwoThousand()  
    73.         {  
    74.             UtilityLib obj =new UtilityLib();  
    76.             Assert.AreNotEqual(1900, obj.calculateDiscount(2000));  
    77.         }  
    78.     }  
    79. }  

  9. Finally build the project and you will notice that the UtilityLibTesting.dll file is created in the project solution directory to be used later during the unit testing in the NUnit application.


    Figure 1.4 NUnitTesting.exe depict

Running Test Case

Until now we have seen the basics of the code, now it is time how to run your tests using the NUnit GUI. To use the GUI application, just simply run the software and target (open the project of) your test assembly where it resides. The test assembly is the class library (or executable) that contains the Test Fixtures. The application will then show you a graphical view of each class. To run the entire suite of tests, simply click the Run button. If you want to run only one Test Fixture or even just a single test, you can double-click it in the tree. After opening the project file, all the methods stated in the DLL file will show up in the left pane as in the following;


Figure 1.5 Test Method Loading

Now hit the Run button on the right side to start the Unit Automotive testing. It will take some time to verify all the conditions given in the test cases. If all the methods function properly as specified by the test condition then the GUI will produce the results in the Green Progress bar as in the following:


Figure 1.6 NUnit Test Report with No Error

In the scenario, if the code has some built-in programming glitches, then they are easily rectified during the NUnit Testing process. The following picture depicts a problem in the TwoThousand() method with the cross sign. Here the report indicates that all the method implementations are working properly except one method:


Figure 1.7 NUnit Test Fail output

We can go deeper in the error by using the Errors and Failure tab in the right bottom. This will display the exact error in the source code as in the following:


Figure 1.8 NUnit Detailed Test Report with Error

Up Next
    Ebook Download
    View all
    View all