Visual Studio Nunit & Rhino Mocks Templates

15 01 2008


1. Introduction
2. System Requirements
3. Download and Install
4. Package Contents
4.1. Test Class Library Project Template
4.2. Test Class ItemTemplate
4.3. Code Snippets
5. Uninstall
6. Suggested Books

1. Introduction

If you’ve been using ‘NUnit’ you found yourself involved in doing repetitive actions like creating test projects and adding test classes and test methods.
If you ever had a try with the ‘Rhino Mocks’ mocking framework you had an extra bit of repetitive code to write, in all of your TestFixture classes.

I was tired of always creating a new test project for each project in my solution and manually add references.
I was tired of always prepare test classes with Setup and Teardown methods as well as other standard elements.

Then I created a standard Project Template creating a test class library, an Item Template creating a Rhino Mocks enabled TestFixture class, and a couple of useful code snippets.

All this stuff is targeted to Visual C# projects.

2. System Requirements

You’ll need the following software:

Visual Studio 2005
NUnit (NUnit-2.4.7-net-2.0.msi)
Rhino Mocks (Rhino.Mocks-3.4.zip)

Important: Project references are based on Nunit default installation path and on Rhino.Mocks.dll being installed into the location %ProgramFiles%\RhinoMocks. To install Rhino in such a path just donwload the .zip file and unzip it there.

Note: If your installation paths are different from the ones specified, you will need to modify project references once created a new test project with my template.

3. Download and Install

First of all download the file: TDDTemplates.vsi that you can find here.
All you have to do is download, double click, and proceed with the installation.
If you want more detailed description of what you are downloading, read further.

The file TDDTemplates.vsi is a Visual Studio installer file, containing:

  1. A Project Template named Test Class Library;
  2. An ItemTemplate named Test Class;
  3. Two Code snippets useful for test driven develpment (TDD Snippet component).

Double-clicking on the installer file you will get a dialog window prompting you to choose wich of the listed items you want to install.
Clicking on the next button you will get a message warning that the installer file is not signed.
If you don’t want to install unsigned content you will need to create this installer by yourself and I will provide you with a brief tutorial in a future post.

If you will click the yes button, checked items will be installed:

  • the Project Template (Test Class Library.zip) will be installed into the location:

%USERPROFILE%\MyDocuments\VisualStudio2005\Templates\ProjectTemplates\VisualC# (where %USERPROFILE% is C:\DocumentsandSettings\username in Windows Xp);

  • the Item Template (Test Class.zip) will be installed into the location:

%USERPROFILE%\MyDocuments\VisualStudio2005\Templates\ItemTemplates\VisualC#;

  • a dialog will allow you to choose were to install Code snippets (TDD.snippet):

if you choose My Code Snippets the snippet file will be installed into the location:
%USERPROFILE%\MyDocuments\VisualStudio2005\CodeSnippets\VisualC#\MyCodeSnippets,

while if you choose Visual C# it will be installed under the Visual Studio installation directory, into the location:
%ProgramFiles%\MicrosoftVisualStudio8\VC#\Snippets\1033\VisualC#.

→ go to top

4. Package Contents

4.1. Test Class Library Project Template
4.2. Test Class ItemTemplate
4.3. Code Snippets

In this paragraph you will find a detailed description of the contents installed by the Visual Studio installer we’re talking about: TDDTemplates.vsi.

4.1. Test Class Library Project Template

When creating a new project, the initial dialog will list a new project template under the Visual C# category: Test Class Library, as shown in the following image.

New Project Dialog

If you rename the project: ProjectName and click ok, a new class library project will be created with the structure shown in the following screenshot of the Solution Explorer window:

Test Project Solution Explorer Screenshot

The file named Class1Tests.cs, created inside the project, contains the code defining the skeleton of a TestFixture class definition:

using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using Rhino.Mocks;

namespace ProjectName
{
    [TestFixture]
    public class Class1Tests
    {
        MockRepository mocks;

        ///
        /// Prepares mock repository
        ///
        [SetUp]
        public void Initialize()
        {
            mocks = new MockRepository();
        }

        ///
        /// template behavior and state testing method
        ///
        [Test]
        public void TestMethod1()
        {
            IDependency dependency = mocks.CreateMock();

            // Record expectations
            using (mocks.Record())
            {
                Expect
                       .Call(dependency.Method1("parameter"))
                       .Return("result");
                dependency.Method2();
            }

            // Replay and validate interaction
            Subject subjectUnderTest;
            using (mocks.Playback())
            {
                subjectUnderTest = new Subject(dependency);
                subjectUnderTest.DoWork();
            }

            // Post-interaction assertion
            Assert.That(subjectUnderTest.WorkDone, Is.True);
        }
    }
}

As you can see the class definition already contains a default implementation of a Test method.
Such method includes the definition of RhinoMocks expectations for a hypothetical object under test.
I chose to use Rhino Mocks new Record-playback Syntax which takes care of calling mocks.ReplayAll() and mocks.VerifyAll() under the hood.
I feel this syntax is very neat and clean providing a clear separation between the moment in which we record expectations and the moment in which we use the object under test.

4.2. Test Class Item Template

When adding a new item to the project, the Add New Item dialog will list a new project template: Test Class.
It is possible that you have to scroll down a little to see the My Templates category, as shown in the following image:

New Item Dialog Box

Selecting the Test Class template, a new class definition file will be created, containing the same class definition you obtained when creating the Test Class Library Project (see previous paragraph).

→ top of paragraph
→ top of post

4.3. Code Snippets

From now on, when writing code, you will have two more intellisense entries in your IDE: TDDtestmethod and TDDusing.

TDDtestmethod will insert a test method definition as shown in the following sequence of images:

TDDtestmethod

Selecting the keyword as in the preceding image will produce the following code:

TDDtestmethod Content

The snippet allows the user to choose the method’s Attribute (defaults to: Nunit.Framework.TestAttribute) and the methods name (defaults to: TestMethod).

TDDusing will insert the two using blocks needed for the Rhino Mocks Record-playback Syntax, as shown in the following sequence of images:

TDDusingRhinoSyntax

Selecting the keyword as in the preceding image will produce the following code:

TDDusingRhinoSyntax Content

The snippet allows the user to choose the instance of Rhino.Mocks.MockRepository
to use for mocking objects.

→ top of paragraph
→ top of post

5. Uninstall

If you want to uninstall the installed content you can simply go to the paths specified in the Download and Install paragraph and delete the correct files:

delete the file: Test Class Library.zip under:
%USERPROFILE%\MyDocuments\VisualStudio2005\Templates\ProjectTemplates\VisualC#

delete the file: Test Class.zip under:
%USERPROFILE%\MyDocuments\VisualStudio2005\Templates\ItemTemplates\VisualC#;

depending on where you chose to install the snippets, find the file TDD.snippet file under:
%USERPROFILE%\MyDocuments\VisualStudio2005\CodeSnippets\VisualC#\MyCodeSnippets,
or under:
%ProgramFiles%\MicrosoftVisualStudio8\VC#\Snippets\1033\VisualC#
and delete it.

That’s all.
Feel free to post a comment if you want to report a bug or to propose enhancement of the templates and snippets.

→ top of paragraph
→ top of post

6. Suggested Books

Some useful reading about Test Driven Development and Nunit can be found in the following books:

Test Driven Development: By Example (The Addison-Wesley Signature Series) Pragmatic Unit Testing in C# with NUnit, 2nd Edition

→ top of post

kick it on DotNetKicks.com

About these ads

Actions

Information

9 responses

22 02 2008
Mike

Hi Matteo,

I can’t seem to find the download link on your page for the file DDTemplates.vsi. Could you please provide us with one?

Thanx and cheers,

Mike

22 02 2008
ilmatte

Hi Mike,

I’m sorry that you can’t find it, you should see a black box.net widget on the right sidebar. It is a flash animation or something similar so I guess that maybe you need some kind of update to see it.

Anyway, I solved the problem: I didn’t know before that is possible to access box.net files by normal links.
Try this and let me know if it works (it should).

http://www.box.net/shared/20nsbuego0

Hope you find it useful :)

Matteo

25 02 2008
Anonymous

Hi Mateo,

Thanks a lot for the link. It worked fine. I’ll install the template and give you some feedback soon,

Take care and thanx again for that great template,

Mike

11 07 2008
Matt

This looks great as I’m new to TDD and am really trying to adopt some better practice to feel more confident in my coding. It’ll probably be a little while before I really get started with this but a template like this is really helpful.

I’ve just downloaded and installed everything but I do get a couple of compile errors relating to IDependancy and Subject not being found. I’m probably missing something obvious but wondered if you could help.

Cheers

Matt

11 07 2008
ilmatte

Hello Matt,

the method: TestMethod1() automatically generated in default test class is
only a sample method to be used as a skeleton for your actual tests.
It contains the Record-Playback syntax of Rhino Mocks.
To make it compile you should replace ‘Subject’ and ‘IDependency’ with the types you’re using in your project.
Subject is the type of the object you want to test, while IDependency is the type of the argument to pass to its constructor.
Rhino Mocks mocking framework wants us to code following the interface oriented programming principles together with inversion of control.
This means that you should provide interfaces for you classes and work with the interfaces every time you can.
Moreover your objects should not know everything about their own behavior. You will inject the behavior in the constructor, for example, passing an object (IDependency) that the ‘Subject’ class will rely on to do some work.
This is the reason why Rhino Mocks only allows us to mock interfaces (e.g.: IDependency) and expects us to pass them as arguments to the objects we’re testing (e.g.: Subject).

You can find more information on mocking in general in this wonderful article by Martin Fowler: Mocks aren’t Stubs
You can find information about Rhino Mocks here and on the author’s wiki pages: here

Hope that this helps.
I’m going to send you two sample classes to make the code compile.

23 03 2011
trace

i can not download ur TDD template , so ,can you email it to me ? thanx

23 03 2011
ilmatte

Sure,

I will send you as soon as possible.At the momentI’m behind a firewall at work. Remember that the templates are a bit obsolete because they refer to old versions of RhinoMocks and Nunit but they should still work if you change the references in the projects created.

Matteo

________________________________

30 11 2011
Bindu

Hi,

I am new to this.
Can u help me include NUnit in my references,
Probably I need to register a .dll somewhere in the GAC or the registry?

Thanx.
Bindu

27 05 2013
Martina

Hi there just wanted to give you a quick heads up and let you know
a few of the images aren’t loading correctly. I’m not sure why but I think its a linking issue.
I’ve tried it in two different web browsers and both show the same results.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: