Running MSTest unit tests via an MSBuild script

The past couple days I've been having fun trying to get some MSTest unit tests to be run from a MSBuild build script. This was so I could run all the tests via one build script via TeamCity without having it tied into TeamCity too heavily.

You can then use the XML Report Processing build step in a TeamCity build configuration to parse the results file and this will give you the tracking of tests.

Huge thanks to Yet Another Blog In Cyberspace for doing most of the legwork that I based my stuff off of. Running MSTest UnitTests using MSBuild

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="RunCIBuild"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<MsTestExePath>C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\mstest.exe</MsTestExePath>
<DoubleQuotes>"</DoubleQuotes>
<OutputPath>$(MSBuildProjectDirectory)\Output</OutputPath>
<MsTestResultPath>$(OutputPath)\MyResults.trx</MsTestResultPath>
<Configuration>Release</Configuration>
</PropertyGroup>


<Target Name="RunCIBuild">
<CallTarget Targets="CompileSolution"/>
<CallTarget Targets="AfterBuild"/>
</Target>

<Target Name="CompileSolution">
<MSBuild Projects="<!--Solution file goes here-->"
Properties="Configuration=$(Configuration)"
Targets="Build">

</MSBuild>
</Target>

<Target Name="AfterBuild">
<ItemGroup>
<TestAssemblies Include="$(MSBuildProjectDirectory)\**\bin\$(Configuration)\*.Test.dll"/>
</ItemGroup>

<PropertyGroup>
<MsTestCommand>"$(MsTestExePath)" @(TestAssemblies->'/testcontainer:"%(FullPath)"', ' ') /resultsfile:"TestResults\Results.trx""</MsTestCommand>
</PropertyGroup>

<Message Text="MsTestCommand: @(TestAssemblies->'/testcontainer:$(DoubleQuotes)%(FullPath)$(DoubleQuotes)', ' ')"
Importance="high"/>

<RemoveDir Directories="TestResults"
Condition="Exists('TestResults')" />
<MakeDir Directories="TestResults" />

<Exec Command="$(MsTestCommand)"
ContinueOnError="true" />
</Target>

</Project>