If you have been following along with ASP.NET MVC, you know testability is a big part of the story. This fact is really driven home when the option to create a test project immediately follows that of a ASP.NET MVC Web Application. This is all really cool – especially the flexible test project templates.
Out of the box, you get the “Visual Studio Unit Test” set which features 25 opinionated Home and Account Controller tests. However, you are not limited to just this template. Nope. You can build your own test project templates (New Project –> Add References, etc –> File –> Export Template), jump through a few hoops (update the vstemplate file settings, copy the exported files to %Program Files%\Microsoft Visual Studio 9.0\Common7\IDE\ProjectTemplates\Csharp\Test\1033, execute devenv /setup, wait a while and then update the registry) and have your own test frameworks appear in the “Test Framework” selectable list. It’s just that easy. 😉
My team is currently using NUnit and Moq so this afternoon I exported a custom template project and put together an install script which I based somewhat on the NUnit MVC Preview 3 Templates. After a few attempts, it all came together.
After running the .bat installer (Install NUnitWithMoq.bat), you will find the “NUnit with Moq” template listed in the “Test Framework” dropdown (see above screenshot .) The new template will also appear under the Test project type templates.
The template includes references to the moq.dll and nunit.framework.dll. Since there’s no way of knowing where each of these files will sit on your machine, the templates make the assumption that they will be inside an “External Dependencies” folder which lives side-by-side with the test project. I suggest putting your “External Dependencies” folder/files in place before you create your MVC and Test project. You shouldn’t have any troubles if you follow this pattern. If not, you’ll merely need to reset the Moq and NUnit references once your test project is created. No big deal.
I’ve provided a screenshot of a sample solution after a new ASP.NET MVC Web Application (MvcApplication1) and NUnit with Moq Test Project (MvcApplication1.Test) are created. As you see, the web project, Moq, NUnit and a handful of other references are included in the test project by default.
The provided tests are basically a ported from the “Visual Studio Unit Test” template. There should be no surprises here as all tests should pass from the get go. Please note that I have only included the C# template for the full version of Visual Studio 2008. I have also included an uninstaller script (Uninstall NUnitWithMoq.bat) so you may install with little worry.