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

3 comments:

  1. .user files usually include user-specific data and should not be put under version control, that’s the only difference.

    As to the second question – I have no idea.

    ReplyDelete
  2. Hi.
    Thanx for the useful post!
    I shortened mine to:
    <PropertyGroup>
    <StartAction>Program</StartAction>
    <StartProgram>C:\Program Files\NUnit\bin\nunit.exe</StartProgram>
    <StartArguments>$(TargetFileName)</StartArguments>
    </PropertyGroup>
    And I put it right into my .csproj.user – is there a difference? If you not include the „/run”, then you can select which test you want to debug from the NUnit GUI.

    Also, would you happen to know why <StartProgram>C:\Program Files\NUnit\bin\nunit-console.exe</StartProgram> does not work?

    ReplyDelete
  3. With VS 2005 Express and NUnit 2.4.6 I found I needed a different start arguments:

    <StartArguments>$(OutDir)\$(TargetFileName) /run</StartArguments>

    ReplyDelete