Archive for the ‘Unit Tests’ Category.

Creating a QUnit Test Project in Visual Studio 2010

You may want to Unit Test your JavaScript code and one library to do this with is QUnit.

QUnit is based on the idea of opening a web page to run your JavaScript tests. So here is how I create a new QUnit project in Visual Studio.

This article assumes that you have the following installed already:

  • Visual Studio 2010 or later
  • The NuGet Add-in for Visual Studio

Step 1 – Create a Visual Studio Project

  1. Open Visual Studio.
  2. Go to File | New | Project.
  3. Select ASP.NET Empty Web Application.
  4. Give the project a name:
    Note: For this walk-thru, I named mine QUnitExample
  5. Click OK.

Step 2 – Import QUnit

Method 1 – Using NuGet

This step requires internet access.

  1. Right-click on your Project and choose Manage NuGet Packages.
  2. Search for QUnit and locate QUnit for ASP.NET MVC.
  3. Click Install next to QUnit for ASP.NET MVC.
  4. Click Close.

You should now see a folder called Content with a QUnit.css file and a folder called Scripts with a QUnit.js file.

Note: The NuGet package had old files, so I had to update them manually following Method 2.

Method 2 – Just downloading the files

If the NuGet package is not up to date, you may want to download the files manually. Follow the steps above to get QUnit through NuGet and if it doesn’t work, download the latest files from the QUnit web site and replace the ones NuGet added to your project with the latest ones.

Step 3 – Create an HTML file to display test results

  1. Right-click on the project and Choose Add | New Item.
  2. Find and choose HTML Page.
  3. Give the page a name.
    Note: I named mine QUnitTestResults.htm.
  4. Open the QUnitTestResults.htm file for editing.
  5. I made the DOCTYPE tag simpler in line 1:
  6. Enter something in the Title: Line 4.
    Note: I called mine QUnit Test Results.
  7. Add a Link to the qunity.css file: Line 5.
  8. Add a script in the body that calls the qunit.js file: Line 8.
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>QUnit Test Results</title>
  <link rel="stylesheet" href="/Content/qunit.css">
</head>
<body>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>
  <script src="/Scripts/qunit.js"></script>
  <script src="/Scripts/tests.js"></script>
</body>
</html>

Step 4 – Create your first QUnit Test

  1. Right-click on the Project and choose Add | New Folder.
  2. Rename the folder to TestScripts.
    Note: I like to keep the test scripts separate from the other scripts.
  3. Right-click on the TestScripts folder and Choose Add | New Item.
  4. Find and choose JScript File.
  5. Give the JavaScript file a name.
    I named mine ExampleTests.js.
  6. Open the ExampleTests.js file for editing.
  7. Add a test method to the ExampleTests.js file.
test("hello test", function () {
    ok(1 == "1", "Passed!");
});

Note: This test is straight from the QUnit home page.

Step 5 – Add the Tests to your HTML file

  1. Open the QUnitTestResults.htm file for editing.
  2. Add a script in the body that calls the ExampleTests.js file: Line 9.
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>QUnit Test Results</title>
  <link rel="stylesheet" href="/Content/qunit.css">
</head>
<body>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>
  <script src="/Scripts/qunit.js"></script>
  <script src="/Scripts/tests.js"></script>
  <script src="/TestScripts/ExampleTests.js"></script>
</body>
</html>

Step 6 – Run the tests

  1. Right-click on the QUnitExample project and choose Set as StartUp Project.
  2. Right-click on QUnitTestResults.htm and choose Set As Start Page.
  3. Click Debug | Start Debugging.

Step 7 – Start testing your JavaScript files

Now you probably want to recreate this project in as an additional project to your production solution (if you haven’t done this already).

It is time to start testing your JavaScript file. If you add the script to your project as a link, then you don’t have to maintain two copies of it.

  1. Right-click on the Scripts folder and choose Add | Existing Item.
  2. Browse to the JavaScript file that you want to test and select it but don’t add it yet.
  3. Click the down arrow next to Add and choose Add as link.
  4. Right-click on the TestScripts folder and Choose Add | New Item.
  5. Find and choose JScript File.
    Note: My file is called MySample.js.
  6. Give the JavaScript file a name.
    Note: I named mine MySampleTests.js.
  7. Open the ExampleTests.js file for editing.
  8. Start adding tests.

Conclusion

This method allows for rudimentary testing of your JavaScript. However, it does not integrate with Visual Studio, or Code Coverage, or Gated Check-ins. So there is a lot more work that needs to be done.

Unit Testing with Parameter Value Coverage (PVC)

Parameter Value Coverage (PVC) is the ability to track coverage of a method based on the common possible values for the parameters accepted by the method.

Current code coverage tools fail to take into consideration the possibility that a value for a parameter is not handled resulting in a bug. However, there may not be any code addressing this value in any way, introducing the possibility of obtaining 100% code coverage or line coverage (LC) without detecting the bug.

If the common values for types, especially primitive types and known types, are documented and methods that use them are required to have a test for each possible parameter value, bugs can be avoided.

The following is a table of parameter value requirements for an int or System.Int32 and string or System.String. A unit test should exist for each of the possible values in order to have 100% PVC.

System.Int32 System.String
  1. A positive integer
  2. A negative integer
  3. Zero
  4. int.MaxValue or 2,147,483,647
  5. int.MinValue or -2,147,483,648
  1. A null string
  2. An empty string, String.Empty, or “”
  3. One or more spaces ” “
  4. One or more tabs ” “
  5. A new line or Environment.NewLine
  6. A valid string.
  7. An invalid or junk string
  8. Unicode characters such as Chinese

Were code coverage tools enhanced to take into account Parameter Value Coverage (PVC), better tests would be written and more bugs would be found.

Such PVC lists could be created for each primitive type and a list of required parameter values to test against for each of primitive type could be standard for each language. You could also create a list of parameter values for you own types though you may find that your own type is actually a collection of primitive types and methods, and if they are tested with PVC, your class is automatically tested with PVC as well.

Finding bugs beyond 100% Code Coverage with PVC

100% code coverage or line coverage (LC) can fail to find many bugs. Developers often write a unit test with only the goal to get as close to 100% LC as they can. Unfortunately, they are only covering the written code, but bugs may exist due to code not written.

Here is a quick example. The method below is a very common example of a piece of code that looks so simple, most assume there is no way there is a bug, but after a brief analysis, the bug becomes obvious.


To get 100% LC, the following test could be used.

1
private void Add_Test()
{
    Adder adder = new Adder();
    var actual = adder.Add(1,2);
    var expected = 3;
    Assert.AreEqual(expected, actual)
}

You now have 100% LC, but have you found all the bugs? No you haven’t. Here are two problems:

  1. An int or System.Int32 is a 32-bit integer with a max value of 2,147,483,647.What happens if you add one or more to the max value?
  2. The minimum value is -2,147,483,648. What happens if you subtract one or more from the minimum value?

How should this problem be fixed?

  • Should you enabled “checked” to disallow overflows?
  • Should you return a long so two 32-bit integers can always be added together?
  • Or should you ignore the issue as it isn’t going to matter in your project?

Your answer may be different depending on your project. I am not going to tell you how to fix this bug in this article, that is not the point. The point is to show that 100% LC failed to find this bug, proving that some thing is missing, some value is not being tracked and reported on.

What is the missing value? Parameter Value Coverage (PVC).

If PVC were taken into account, the test above only provides 20% coverage as only one of the five integer value types were tested. Reaching 80% to 100% PVC would have found this bug.

Every bug that is found internally will cost your business far less money overall than if a customer finds the bug.

Return to C# Unit Test Tutorial

Better Unit Tests in C#

When you test the right thing, you get better unit tests. Better unit tests often lead to better design, testable design, and easier maintainability of code.

Look at an example of testing a Copy() method in a Person object. You will see that as you unit test this method, you are forced to think. If you think about what you really want to test (instead of just thinking about 100% coverage), and test for that, it will lead you to changing your code for the better.

With a Copy() method, you want to make sure that every property in the Person object is copied. You want to make sure that any new Property added in the future is copied.

Lets see if we can do this. Lets start with our simple example Person object with a Copy() method and lets test the copy method.

using System;

namespace FriendDatabase
{
    public class Person
    {
        #region Properties
        public int Age { get; set; }
        public String FirstName { get; set; }
        public String LastName { get; set; }
        #endregion

        #region Methods
        public Person Copy()
        {
            Person retPerson = new Person();
            retPerson.Age = this.Age;
            retPerson.FirstName = this.FirstName;
            retPerson.LastName = this.LastName;
            return retPerson;
        }
        #endregion
    }
}

Lets list the three most obvious tests for the copy method.

  1. Age is the same value.
  2. FirstName is the same value.
  3. LastName is the same value.

If you are an expert at Unit Testing, you are probably already thinking that there are more tests to run that just these three tests.0

A simple Unit Test

A test for this that would give use 100% code coverage and covers the three most obvious tests would be as follows:

[Test]
public void Person_Copy_Test()
{
    // Step 1 - Arrange
    Person p = new Person() { FirstName = "John", LastName = "Johnson", Age = 0 };

    // Step 2 - Act
    Person copy = p.Copy();

    // Step 3 - Assert
    Assert.AreEqual(p.Age, copy.Age);
    Assert.AreEqual(p.FirstName, copy.FirstName);
    Assert.AreEqual(p.LastName, copy.LastName);
}

The code coverage is now 100%. But is this a good test? No.

What are the problems with our tests?

Problem 1 – The Unit Test does not guarantee every property is copied

In the Person.Copy() method, comment out the line that copies the Age. Run the test again.

Oops! The test still passes.

What is the problem? Well, int defaults to zero.

Change the age to a value other than zero and try again.  The test now fails.

[Test]
public void Person_Copy_Test()
{
    // Step 1 - Arrange
    Person p = new Person() { FirstName = "John", LastName = "Johnson", Age = 25 };

    // Step 2 - Act
    Person copy = p.Copy();

    // Step 3 - Assert
    Assert.AreEqual(p.Age, copy.Age);
    Assert.AreEqual(p.FirstName, copy.FirstName);
    Assert.AreEqual(p.LastName, copy.LastName);
}

This fixed this one problem.

Is the test good enough now? Of course not.

Problem 2 – The Unit Test does not guarantee every property is copied

Wait, you might be saying that my problem 2 is named the same as problem 1 and you might think this is a typo. It is not a typo.

We still have a similar problem to the first problem.

Imagine a new user developer takes over the code, and decides that a MiddleName property is needed. Go ahead and add a middle name property. Don’t modify the Copy() method yet. Now run your Unit Test again.

Our one test still passes.

Shouldn’t there be a test that fails because the copy is now failing to copy to all properties? Yes there should. We have just identified a new test that actually includes the previous three tests. The goal of our three tests were all the same overall goal. Our three tests were actually slightly wrong. Instead we really had only one test: Test that when Copy() is invoked, all properties should be copied.

Now that we have gain more insight on what we are actually testing, how do we test it? How do we test all properties. One idea might be to use reflection.

[Test]
public void Person_Copy_Test()
{
    // Step 1 - Arrange
    Person p = new Person() { FirstName = "John", LastName = "Johnson", Age = 25 };

    // Step 2 - Act
    Person copy = p.Copy();

    // Step 3 - Assert
    PropertyInfo[] propInfo = typeof(Person).GetProperties();
    foreach (var prop in propInfo)
    {
        object pObj = typeof(Person).GetProperty(prop.Name).GetValue(p, null);
        object copyObj = typeof(Person).GetProperty(prop.Name).GetValue(copy, null);
        Assert.AreEqual(pObj, copyObj);
    }
}

At first this looked like a good idea, because it will check each property for us, even properties added in the future. However, it turns out that because int and string have default values, This test didn’t exactly test what we wanted to test. This test still passes when it should fail and that is a problem.

Remember the test: to test that when Copy() is invoked, all properties should be copied.

We need guarantee that each property was called and to do this. If only we were using an interface, then we could mock the interface and assert that each public property were called…A good rule to live by when developing is if you hear yourself say or you think “if only…” you should actually try implementing the “if only…” you just thought of. So lets do that.

This is a little longer of a solution but a better design, so here are some steps to get there.

  1. Create an IPerson interface that has the properties and methods we want to guarantee exist.
    using System;
    
    namespace FriendDatabase
    {
        public interface IPerson
        {
            int Age { get; set; }
            String FirstName { get; set; }
            String MiddleName { get; set; }
            String LastName { get; set; }
    
            IPerson Copy();
            void CopyTo(IPerson inIPerson);
        }
    }
    
  2. Change the person object so that you can never get a Person object, you always get an IPerson.
  3. We also need to be able to mock the instance of IPerson that is getting created by the Copy method and our current design doesn’t allow for that. Lets change our Copy method and add a CopyTo method to make this possible.
    using System;
    
    namespace FriendDatabase
    {
        public class Person : IPerson
        {
            #region Constructor
            ///
    <summary> /// Nobody should use Person, but on GetPerson()
     /// which returns and IPerson
     /// </summary>
            protected Person()
            {
            }
            #endregion
    
            #region Properties
            public int Age { get; set; }
            public String FirstName { get; set; }
            public String MiddleName { get; set; }
            public String LastName { get; set; }
            private String NickName { get; set; }
            #endregion
    
            #region Methods
            public static IPerson GetPerson(string inFirstName, string inMiddleName, String inLastName = null, int inAge = 0)
            {
                return new Person()
                {
                    FirstName = inFirstName,
                    MiddleName = inMiddleName,
                    LastName = inLastName,
                    Age = inAge
                };
            }
    
            public IPerson Copy()
            {
                IPerson retIPerson = new Person();
                CopyTo(retIPerson);
                return retIPerson;
            }
    
            public void CopyTo(IPerson inIPerson)
            {
                inIPerson.Age = this.Age;
                inIPerson.FirstName = this.FirstName;
                inIPerson.LastName = this.LastName;
            }
            #endregion
        }
    }
    
  4. Now we need a Mocking tool. Download you favorite mocking library (RhinoMocks, NMock2, or MOQ). I am going to use NMock2 which can be downloaded here: NMock2
  5. Lets put the mocking library in a lib directory in your test project.
  6. Add a reference to the dll.
  7. Now lets change our test. Lets go ahead and use the reflection still, but this time, we want to guarantee that each property was called.
    [Test]
    public void Person_Copy_All_Properties_Copied_Test()
    {
        // Step 1 - Arrange
        Mockery mock = new Mockery();
        IPerson p = Person.GetPerson("John", "J.", "Johnson", 25);
        IPerson mockIPerson = mock.NewMock();
        PropertyInfo[] propInfo = typeof(IPerson).GetProperties();
    
        // Step 2 - Expect
        foreach (var prop in propInfo)
        {
            Expect.AtLeastOnce.On(mockIPerson).SetProperty(prop.Name);
        }
    
        // Step 3 - Act
        p.CopyTo(mockIPerson);
    
        // Step 4 - Assert
        mock.VerifyAllExpectationsHaveBeenMet();
    }
    

    Note: NMock2 requires a slight variation of the Arrange, Act, Assert (AAA) unit test model in that it is more Arrange, Expect, Act, Assert (AEAA), which is just as good and just as clean. One could argue that the expectations are part of the Arrange and I would somewhat agree with that too.

  8. Ok, now run your test again and it should fail because we are not calling MiddleName in our CopyTo() method. You have now written the correct unit test for the goal.

So by taking time to think of the correct test and Unit Testing the correct test, solving the right problem, we gained a few benefits.

  • Better future maintainability
  • Better design
  • Testable design

Now hopefully you can go and do this when you write your Unit Tests.

Return to C# Unit Test Tutorial

Mocking an internal interface with InternalsVisibleTo in C#

Previously, posted instructions for setting this up.

How to Mock an internal interface with NMock2?

Attached is a sample solution that demonstrates actually implementing this.

ExampleOfIVT.zip

How to Mock an internal interface with NMock2?

I was attempting to mock an internal interface with NMock2 and no matter what I tried I continued to get the following failure.

Test 'M:ExampleOfIVT.PersonTests.FirstTest' failed: Type is not public, so a proxy cannot be generated. Type: ExampleOfIVT.IPerson
	Castle.DynamicProxy.Generators.GeneratorException: Type is not public, so a proxy cannot be generated. Type: ExampleOfIVT.IPerson
	at Castle.DynamicProxy.DefaultProxyBuilder.AssertValidType(Type target)
	at Castle.DynamicProxy.DefaultProxyBuilder.CreateInterfaceProxyTypeWithoutTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options)
	at NMock2.Monitoring.CastleMockObjectFactory.GetProxyType(CompositeType compositeType)
	at NMock2.Monitoring.CastleMockObjectFactory.CreateMock(Mockery mockery, CompositeType typesToMock, String name, MockStyle mockStyle, Object[] constructorArgs)
	at NMock2.Internal.MockBuilder.Create(Type primaryType, Mockery mockery, IMockObjectFactory mockObjectFactory)
	at NMock2.Mockery.NewMock[TMockedType](IMockDefinition definition)
	at NMock2.Mockery.NewMock[TMockedType](Object[] constructorArgs)
	PersonTests.cs(59,0): at ExampleOfIVT.PersonTests.FirstTest()

Obviously I have a project, ExampleOfIVT, and a test project, ExampleOfIVTTests.

All the Google searching suggested that I should be adding these lines to my AssemblyInfo.cs file in the ExampleOfIVT project but these line did NOT work.

Please not that I downloaded NMock2 from here: http://sourceforge.net/projects/nmock2/

[assembly: InternalsVisibleTo("Mocks")]
[assembly: InternalsVisibleTo("MockObjects")]

Turns out that they have changed to use Castle.DynamicProxy and so the only assembly I needed was this one.

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

Return to C# Unit Test Tutorial

Beginning Unit Testing Tutorial in C# with NUnit (Part 2)

Continued from Beginning Unit Testing Tutorial in C# with NUnit (Part 1)

Step 4 – Create your first NUnit test

  1. Choose a method from the class you want to test. For example, SimpleAddSubtractTool has the Add() method.
  2. Create a corresponding test method.  Try to name your test as follows: Method_Param1_Param2_Test() and you can add any other words to help clarify the test.
  3. Place the [Test] attribute above the test function.
  4. Add code to test the Add function.
    Note: A common testing method is Arrange Act Assert (AAA). Lets write the code in our method with this in mind.

            [Test]
            public void Add_1_And_2_Test()
            {
                // Step 1 - Arrange (Basically create the objects)
                SimpleAddSubtractTool tool = new SimpleAddSubtractTool();
    
                // Step 2 - Act
                int actual = tool.Add(1, 2);
    
                // Step 3 - Assert
                int expected = 3; // This makes it clear what you expect.
                Assert.AreEqual(expected, actual);
            }
    
  5. Now Create a similar test for the Subtract method.

You are now ready to run your test.

Step 5 – Run the test

You might think you can just right-click on the project and choose Run Tests. However, by default you cannot do this. To add a plugin called TestDriven.NET that provides this right-click Run Tests functionality,  see this post.

How to run a Unit Tests in Visual Studio?

Now you should be able to run your tests.

Step 6 – Check your code coverage

Code Coverage is basically the number of lines of code tested divided by the total number of lines of code.  If you have 10 lines of code but your test only touches five lines of code, you have 50% code coverage. Obviously the goal is 100%.

Again, by default you cannot just right-click and run the Unit Tests unless you have installed TestDriven.NET.

You should now see your code coverage. The Add() method should be 100% covered.

Step 7 – Parameter Value Coverage

You may think that you are good to go. You have unit tests, and your code is 100% covered (based on line coverage). Well, there are bugs in the code above and you haven’t found them, so you are not done. In order to find these bugs you should research the possible parameter values. You will find some more tests to run. I coined the term Parameter Value Coverage (PVC). Most code coverage tools completely ignore PVC.

Both parameters are of the type int or System.Int32. So these are 32 bit integers.

How many possible values should be tested to have 100% PVC? You should have at least these five:

  1. Positive value: 1, 2, 3, …, 2147483647.
  2. Negative vlaue: -1, -2, -3, …, -2147483648.
  3. Zero
  4. int.MaxValue or 2147483647.
  5. int.MinValue or -2147483648.
So while we have 100% code coverage we only have 20% PVC.
So looking at these five possible values, the following questions come to mind.
  • What happens if you add 1 (or any number for that matter) to int.MaxValue?
  • What happens if you subtract 1 (or any number for that matter) from int.MinValue?

Well, write unit tests to answer these questions. Adding 1 to 2,147,483,647 will fail if the expected value is the positive integer 2,147,483,648. In fact, the answer is the negative integer -2,147,483,648. Figure out why this is. Determine where the bug is, then decide how to handle it.

[Test]
        public void Add_Int32MaxValue_and_1_Test()
        {
            // Step 1 - Arrange (Basically create the objects and prepare the test)
            SimpleAddSubtractTool tool = new SimpleAddSubtractTool();

            // Step 2 - Act (Bacically call the method)
            int actual = tool.Add(int.MaxValue, 1);

            // Step 3 - Assert (Make sure what you expect is true)
            int expected = 2147483648; // This won't even compile...
            Assert.AreEqual(expected, actual);
        }

It is up to you to decide how to fix this bug, as the right way to fix this bug is not part of this article.

Return to C# Unit Test Tutorial

Beginning Unit Testing Tutorial in C# with NUnit (Part 1)

So how do you get started with Unit Testing? Well, you need a Unit Testing framework and some basic know how. This article will help you with both.

NUnit is a commonly used testing framework for C#. Well, NUnit has a guide  but I found it incomplete for a newbie, though perfectly acceptable for an experienced developer.
http://nunit.org/index.php?p=quickStart&r=2.6

Lets assume that you have a project with this class:

namespace NUnitBasics
{
    public class SimpleAddSubtractTool
    {
        public int Add(int value1, int value2)
        {
            return value1 + value2;
        }

        public int Subtract(int value1, int value2)
        {
            return value1 - value2;
        }
    }
}

You need to test these methods and find bugs in them and despite how simple they appear, there are bugs in the above methods.

Step 1 – Install NUnit

  1. Go to this url and download the latest version of NUnit.
    http://nunit.org/?p=download
  2. Run the installer.

Step 2 – Create an NUnit testing project in Visual Studio

You can do this manually, as described below, or you can download my templates: NUnit Project Template for Visual Studio

Part 1 – Creating the Project

  1. In Visual Studio, open the solution that holds the project and code that needs to be tested.
  2. Right-click on the solution and choose Add | New Project.
  3. In the tree on the left, select Visual C# | Windows.
    Note: You would think you would select a Test project, but that is for the testing framework built into Visual Studio, MSTest.
  4. Click to highlight Class Library.
  5. Provide a project name.
    Important: It is usually best practice to give the test project the same name as the project it is test only with the word “test” at the end. For example, a project called MyProject would have a corresponding test project called MyProjectTests.
  6. Click Ok.

Part 2 – Configuring the project

  1. Click Reference | Add Reference.
  2. Click the first tab: .NET
  3. Find and add nunit.framework and nunit.mocks.
  4. Click Reference | Add Reference (again).
  5. Choose Projects.
  6. Select the project that is being tested.
  7. Click Ok.
  8. Delete the Class1.cs as it is not used.

Step 3 – Start your first Unit Test

You can add a class and manually change it to be an NUnit test class as described below, or you can download my template: NUnit Item Template for Visual Studio

Part 1 – Create the class file

  1. Right-click on your project and choose Add | Class.
  2. Name the class after the class you are going to test. For example, a class called SimpleAddSubtractTool would have a corresponding test class called SimpleAddSubtractToolTests.
  3. Click OK.

Part 2 – Convert to an NUnit class file

  1. Add a using reference to NUnit.Framwork.
  2. Add the [TestFixture] attribute above the class name.
  3. Add Setup and Tear down attributes and methods if needed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;

namespace NUnitBasicsTests
{
    /// <summary>
    /// A test class for ...
    /// </summary>
    [TestFixture]
    public class SampleTest
    {
        #region Setup and Tear down
        /// <summary>
        /// This runs only once at the beginning of all tests and is used for all tests in the
        /// class.
        /// </summary>
        [TestFixtureSetUp]
        public void InitialSetup()
        {

        }

        /// <summary>
        /// This runs only once at the end of all tests and is used for all tests in the class.
        /// </summary>
        [TestFixtureTearDown]
        public void FinalTearDown()
        {

        }

        /// <summary>
        /// This setup funcitons runs before each test method
        /// </summary>
        [SetUp]
        public void SetupForEachTest()
        {
        }

        /// <summary>
        /// This setup funcitons runs after each test method
        /// </summary>
        [TearDown]
        public void TearDownForEachTest()
        {
        }
        #endregion
    }
}

You are now ready to create your first test.

Note: For this basic class you can actually delete the Setup and Tear down region as it won’t be used, however, it is good to know how to use it when you get started.

Beginning Unit Testing Tutorial in C# with NUnit (Part 2)

Return to C# Unit Test Tutorial

How to run Unit Tests in Visual Studio?

NUnit does not currently have a plugin for Visual Studio that allows you to run test right from Visual Studio. However, it can be done.

You can use a number of tools but the tool I prefer is TestDriven.NET.

Step 1 – Download and Installation

  1. Go to the TestDriven.NET web site.
  2. Click the download link.
  3. Download the appropriate version (Enterprise, Professional, or Personal).
  4. Close Visual Studio.
  5. Install TestDriven.NET.

Step 2 – Running Unit Tests

  1. Open your solution that has a test project in Visual Studio.
  2. Right-click on your test project and you should see a Run Test(s) and a Test With option.
  3. Select Run Test(s).
You are now running tests just by right-clicking in Visual Studio.

Notice that you can also run tests in the Debugger and with Coverage and with Performance.

Unit Test Stub Code Generator for Covering Arrays

Download Unit Test Stub Code Generator for Covering Arrays

The software can be downloaded here. Sorry, there is not an installer yet.

Installing Unit Test Stub Code Generator for Covering Arrays

  1. Copy the folder “Unit Test Stub Code Generator for Covering Arrays 1.0″ to anywhere on a Windows computer.
  2. Copy the Config directory to %ProgramData%\UnitTestGenerator. You will likely have to create that directory manually first.

That is it.

Try these sample method signatures.

public void MyFunction(string inString, bool inBool)

public void MyFunction(string inString, int inInt, bool inBool)

public void MyFunction(Person inPerson, string inString, int inInt)
{
    // Do some stuf
}

Return to C# Unit Test Tutorial

NUnit Project and Item Templates for Visual Studio

Here is an NUnit Project Template for Visual Studio.

  1. Download this template: NUnit Project
  2. Place this zip file into the %USERPROFILE%\Documents\Visual Studio 2010\Templates\ProjectTemplates\Visual C#.
  3. Create a new Visual Studio Project and choose NUnit Project from the list of C# projects.

Here is an NUnit Item Template for Visual Studio.

  1. Download this template: NUnit Test
  2. Place this zip file into the %USERPROFILE%\Documents\Visual Studio 2010\Templates\ItemTemplates\Visual C#.
  3. Add a new item to an NUnit Project and choose NUnit Test from the list of C# items.