Click here to Skip to main content
15,346,564 members
Articles / Programming Languages / C#
Posted 8 Aug 2008


76 bookmarked

NUnit Test Case Code Generator

Rate me:
Please Sign up or sign in to vote.
4.59/5 (17 votes)
13 Aug 2008CPOL6 min read
Automatically generate NUnit test case code template starting from method to test


Whenever you need to test a new code library with a lot of public methods and without a unit test case written from the developer, you can automatically generate a NUnit test case, method by method, with NUTestCaseCodeGenerator, that allows you to generate a C# source code template for NUnit test case starting from library methods to test.

To run the application, the following is required:

  • Windows XP SP2 or Windows 2003 Server SP1
  • IIS 5.1/6.0 (add from Windows Components)
  • Visual Studio 2005
  • Microsoft Framework 2.0 (that will already be installed by SP2 or VS05)
  • NUNIT Framework 2.4.7

NUTestCaseCodeGenerator doesn't check system requirements, it's only a starting idea for didactic use and does not have a GUI or written code optimized.


A unit test is a test for the smallest testable part of an application (methods). Unit testing is typically done by software developers to ensure that the code they have written meets software requirements and behaves as the developer intended.

Test-driven software development technique requires that an automated unit test, defining requirements of the code, is written before each aspect of the code itself. These tests contain assertions that are either true or false.

Running the tests gives rapid confirmation of correct behavior as the code evolves and is refactored. Testing frameworks like NUnit provide a mechanism for creating and running sets of automated test cases. In test-driven development, each feature begins with writing a test, so for each method, the developer should have to write a unit tests related case. Every method will have more than one test case depending on the complexity of the method signature.

In the real world, developers do not have the time to write a unit test and the software is tested only during integration test or system test phases, but, of course, in these phases not all methods or modules interactions with all possible parameters are called and not all regressions are checked. Consequently, test code coverage and software quality is low, and integration and system test phases are very hard.

Another consideration regarding the importance of unit tests, even if making unit tests takes a lot of time, is that they are the only types of tests that are really automatizable, because you're working with the code, so unit tests can run without a tester. This is better because integration and system tests are difficult to make automatizable and are time consuming, because you are working with GUI interaction.

As I have already said, the real world of software development is not "test-first" but "test-last", and there isn't a clear separation between main test phases (Unit, Integration and System), thus, more and more often, a mix is chosen. Take advantage of the unit test framework in the integration and system test phases, using framework utility functionality for the automatic evaluation of the results without human action, and embedding inside unit test cases, not a single method call, but a procedure as sequences (methods to call and GUI interaction). This is a different way of testing main software user functionality, which is typically tested manually during integration and system test phases.

There are two problems to make a test really automatic. First, make the "action" automatic (call the method for library tests or click the button for GUI test). Second, make automatic the evaluation of the action results.

There are many frameworks that help you to automatize software tests, and you make them work together. I just spoke of NUnit for code library unit testing, but it is not the only one, there is WatiN for ASP.NET pages and NUnitForms for .NET Windows Forms.

In the example below, you can see an unconventional NUnit test, usable for automatized integration and system tests, where two test frameworks work together for executing a sequence that is more complex than a unit test.

This could be a use (or abuse) of a unit test but, as I have already said, this is for the real world.

using System;
using NUnit.Framework;
using Watin.Core;

namespace ExampleLibraryToTest_NU
    [TestFixture, Description("ExampleLibraryToTest.Class1")]
    public class Class1_Fixture
        [Test, Description("ASPNET GUI testing")]
        public void ASPNET_GUI_Testing_TC()
            //This is WatiN - create IE instance, open the browser and go to default page
            IE ie = new IE("http://localhost:1036/WebSite1/Default.aspx");

            //This is NUnit - check that ie instance is not null
            Assert.IsNotNull(ie, "Error creating IE instance.");

            //This is WatiN - get first cell value of the HTML table
            string cellVal = ie.TableCell(Find.ByIndex(0)).Text;

            //This is NUnit - check that first cell value is correct
            Assert.That(cellVal, Is.EqualTo("ValueExpected"), "Error");

            //This is WatiN - Click OKButton
            ie.Button(Find.ById(New Regex(OKButton))).Click()

            //This is NUnit - check something by code
            string ret = UserLibrary.GetResultOfClick();
            Assert.That(ret, Is.EqualTo("ValueExpected"), "Error");

            //Other steps of procedure......

Using the Code

Before starting the application, open a *.config file and set the NUnit installation path:

add key="NUnitFrameworkInstall" value="C:\Program Files\NUnit 2.4.7\"

NUTestCaseCodeGenerator works in two steps:

First load in the left side panel .NET assembly with the library to test, drag and drop from the left side panel to the right side panel a class with method to test and check the desired method. From the right side panel context menu, select the first option, "Create NUnit source code and VS project".

Visual Studio will be opened with a project template of NUnit test case source code, so you will have to valorize the method input variable and the NUnit statement for return evaluation, Assert.That(return, Is.EqualTo("put expected value here")) and build the project.

For example, if you have to test a method with a signature like this, with...

public bool M3_WithClass(int MyInt1, int MyInt2, Class1_2 cl1_2)

... this will be the Nunit test case code automatically generated by the application:

namespace ExampleLibraryToTest_NU
    [TestFixture, Description("ExampleLibraryToTest.Class1")]
    public class Class1_Fixture
        [Test, Description("M3_WithClass")]
        public void M3_WithClass_TC()
            //Create a Class instance
            Console.Out.WriteLine( "Try to instance Class" );
            ExampleLibraryToTest.Class1 myClToTest = new ExampleLibraryToTest.Class1();
                "Error creating ExampleLibraryToTest.Class1 instance.");
            Console.Out.WriteLine("instance ok");

            //Declare method input variable, remember to valorize it.
            System.Int32 MyInt1 = 0;
            System.Int32 MyInt2 = 0;

            //Create a Class instance
            Console.Out.WriteLine( "Try to instance Class" );
            ExampleLibraryToTest.Class1_2 cl1_2 = new ExampleLibraryToTest.Class1_2();
                "Error creating ExampleLibraryToTest.Class1_2 instance.");
            Console.Out.WriteLine("instance ok");

            //Test the method
            Console.Out.WriteLine("Call the method");
            //************ Method to test ************ 
            System.Boolean ret = myClToTest.M3_WithClass(MyInt1,MyInt2,cl1_2);
            //Remember to valorize expected return 
            Assert.That(ret, Is.EqualTo("Boolean"), "Error");
            Console.Out.WriteLine("Method ok");

In the second step load in the left side panel NUnit assembly with a test case just created, drag and drop from the left side panel to the right side panel a class fixture with a test case. From the right side panel context menu, select the second option "Create NUnit project and WebApplication".

A NUnit GUI for running a test case from the GUI application will be created and opened automatically and a Web page made to call the same test case from a different environment caller. This allows you to check security and access problems because, in a Windows application process, the owner is a logon user, otherwise, in a Web application process the owner depends on the configuration.

In the zip file attached, there is a .NET library ExampleClassLibraryToTest for demo use, try to load it.

Points of Interest

Here is a brief summary of points of interest because the code is too large (see the source attached):

  1. The core of application is a recursive method (RecursiveInspecting()) to explore an assembly with Reflection and load a treeview (see INSPECTING region in Actions.cs).
  2. Create a Visual Studio project: directory structure and AssemblyInfo.cs, projectName.csproj, NUnitTestCase.cs files (see VS PROJECT region in Actions.cs).
  3. Create an NUnit project file: XML file .nunit (see CreateNUnitProj() method in Actions.cs).
  4. Create a Web Application in local IIS: create a virtual directory, directory structure on wwwroot and all files and DLL (see WEB APPLICATION region in Actions.cs).

To Do

All files, XML, CS and others are built with the StringBuilder class like a text file, but it would be better to use an appropriate builder for each type of file, or use class Serialization instead of a builder (a more elegant solution).


  • 8th August, 2008: Initial post
  • 12th August, 2008: Article updated
  • 13th August, 2008: Source code and article updated


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer
Italy Italy
No Biography provided

Comments and Discussions

GeneralMy vote of 5 Pin
raiserle9-Apr-16 5:18
Memberraiserle9-Apr-16 5:18 
QuestionNewly Recoded Version (I did it!) Pin
AndyHo7-Nov-12 4:01
professionalAndyHo7-Nov-12 4:01 
AnswerRe: Newly Recoded Version (I did it!) Pin
msp.netdev7-Nov-12 8:25
Membermsp.netdev7-Nov-12 8:25 
QuestionRe: Newly Recoded Version (I did it!) Pin
Rtananabh22-May-13 3:04
MemberRtananabh22-May-13 3:04 
QuestionDid not work with NUnit 2.6 Pin
Debjit Kar11-May-12 9:42
MemberDebjit Kar11-May-12 9:42 
AnswerRe: Did not work with NUnit 2.6 Pin
zaighummalik5-Aug-12 21:34
Memberzaighummalik5-Aug-12 21:34 
GeneralDid not work with Nunit 2.5.3 Pin
paul_g1235-Feb-10 1:35
Memberpaul_g1235-Feb-10 1:35 
GeneralRe: Did not work with Nunit 2.5.3 Pin
Nandkishor Phalke5-Oct-10 23:48
MemberNandkishor Phalke5-Oct-10 23:48 
Questionnunit testing Pin
nkviknesh18-May-09 2:21
Membernkviknesh18-May-09 2:21 
AnswerRe: nunit testing Pin
nkviknesh26-May-09 18:50
Membernkviknesh26-May-09 18:50 
GeneralRe: nunit testing Pin
Santhoshi Miryala1-Dec-11 23:53
MemberSanthoshi Miryala1-Dec-11 23:53 
QuestionReflectionTypeLoadException Pin
Member 366454723-Apr-09 2:36
MemberMember 366454723-Apr-09 2:36 
GeneralGood submission Pin
Mark Nahirny18-Aug-08 15:20
MemberMark Nahirny18-Aug-08 15:20 
GeneralRe: overloaded methods issue Pin
Mark Nahirny19-Aug-08 9:46
MemberMark Nahirny19-Aug-08 9:46 
GeneralIssues with the code Pin
pdoshi14-Aug-08 9:15
Memberpdoshi14-Aug-08 9:15 
GeneralYou have a few spelling errors in the logging messages of the article [modified] Pin
Paul B.11-Aug-08 15:50
MemberPaul B.11-Aug-08 15:50 
GeneralRe: When I see "Try to istance Class" I run away Pin
Roefes12-Aug-08 0:36
MemberRoefes12-Aug-08 0:36 
GeneralRe: Pin
Paul B.12-Aug-08 3:00
MemberPaul B.12-Aug-08 3:00 
GeneralRe: When I see "Try to istance Class" I run away Pin
msp.netdev13-Aug-08 8:54
Membermsp.netdev13-Aug-08 8:54 
GeneralGeneral remark Pin
icestatue8-Aug-08 7:53
Membericestatue8-Aug-08 7:53 
GeneralRe: General remark Pin
ShreeramSigdel23-Oct-08 8:52
MemberShreeramSigdel23-Oct-08 8:52 

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.