Sunday, December 28, 2008

Running unit tests during builds in Visual Studio .NET - part 2

Hi all,

as I've mentioned in my previous post it's quite easy to implement running tests during build process of VisualStudio. Now not everyone is comfortable with using a set of 3rd party tasks to do simple things. This time we're going to simplify things a little bit and use the Exec task of MSBuild that already comes with the standard installation.

We're going to start as previously with the XML style sheet that will convert the XML output to a format that's understandable by VisualStudio. Save the following content into your project under VSTestFormat.xslt:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="">
<xsl:output method='text'/>

<xsl:template match="/">

<xsl:template match="test-results">
<xsl:apply-templates select="//test-case[failure]"/>

<xsl:template match="test-case">
<xsl:value-of select="substring-before(substring-after(failure/stack-trace, ' in '), ':line')"/>
<xsl:value-of select="normalize-space(substring-after(substring-after(failure/stack-trace, ' in '), ':line '))"/>
<xsl:text> : warning NU001: </xsl:text>
<xsl:value-of select="@name"/><xsl:text>: </xsl:text>
<xsl:value-of select="normalize-space(child::node()/message)" />
<xsl:text disable-output-escaping='yes'>&#xD;&#xA;</xsl:text>

Next we're going to add the task after building the project (that goes into the [projectname].csproj file):

<Target Name="AfterBuild">
<Exec Command='"$(ProgramFiles)\Nunit 2.4.8\bin\nunit-console.exe" $(OutputPath)$(AssemblyName).dll /xml=$(OutputPath)nunit-results.xml /transform=VSTestFormat.xslt /noshadow /nologo /nodots' />

That's it! Now when you'll build your project it is going to run tests before returning to the editor and all failing tests are converted to a list of entries in the "Error List" window of VisualStudio.

Let me make one note here: This solution works perfectly with all IDEs - the full-blown one as well as with Express editions.

For those that don't like to experiment and just want to start building tests here's a VisualStudio template ready to use. Please note that it's provided "AS-IS" without any warranty so use it at your own risk.

Happy building!

No comments: