Monday, 2 July 2007

Debugging NUnit tests in Visual Studio 2005 Express

VS2005 Express imposes many limitations on it's users as a trade-off for being free. It's main disadvantage IMHO is that it provides no support at all for unit tests. Fortunately there is a simple workaround for this. No, I am not talking about hacking VS to accept plugins as TestDriven.NET used to do. What I wanted to have was the ability to click "Debug" on a library project containing test and have it launched - inside the Visual Studio debugger.


This trick requires adding a tiny bit of magic code to the .csproj file:



<PropertyGroup>
<Nunit_Path Condition="'$(NUNIT_PATH)' == ''">C:\Program Files\NUnit</Nunit_Path>
<StartAction>Program</StartAction>
<StartProgram>$(NUNIT_PATH)\bin\nunit.exe</StartProgram>
<StartArguments>/run $(TargetFileName)</StartArguments>
<!--.csproj.user overwrites those values!-->
</PropertyGroup>

This should be pasted at the end of the project file, after <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> and just before </Project>


Save the changes and open the project in Visual Studio. You can now launch the tests by clicking "Debug->Start Without Debugging" and debug them with "Debug->Start Debugging". One caveat, though - this assumes that NUnit is installed in C:\Program Files\NUnit. If your instalation directory is different, you have to set the environment variable NUNIT_PATH accordingly.


On a side note, some MSBuild/VS2005 quirks:


  • StartProgram has to point to an absolute location (i.e. not to a program in PATH)

  • StartWorkingDirectory has to be unset (or it could point to $TargetDir, if only I could get it to resolve instead of returning "@(_OutputPathItem->'%(FullPath)')" literally)

  • all those properties can be set from Professional version - Express does not show edit boxes for most of them