65.9K
CodeProject is changing. Read more.
Home

XUnit and MSBuild

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.59/5 (3 votes)

May 23, 2015

CPOL
viewsIcon

8058

XUnit and MSBuild

Recently, I needed to execute xUnit tests with MSBuild, so I've spent some time for creating a MSBuild project running the tests. Luckily, xUnit already has MSBuild tasks so I just needed to hook it up.

I wanted to search for all xUnit unit test DLLs inside a folder and run the tests there. So I'm searching for xunit.core.dll file to get all the folders eventually containing such DLLs and then search all these folders for a pattern - *.Tests.dll. When the tests DLLs are found, xunit task is run for all of them. So, here's the result .proj file:

<?xml version="1.0" encoding="utf-8"?>
<Project
    DefaultTargets="Test"
    xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

    <UsingTask
      AssemblyFile="xunit.runner.msbuild.dll"
      TaskName="Xunit.Runner.MSBuild.xunit"/>

    <UsingTask TaskName="GetAssemblies" TaskFactory="CodeTaskFactory" 
               AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
        <ParameterGroup>
            <Path ParameterType="System.String" Required="true" />
            <XUnitFileName ParameterType="System.String" Required="false"/>
            <TestsSearchPattern ParameterType="System.String" Required="false"/>
            <Assemblies ParameterType="System.String[]" Output="true" />
        </ParameterGroup>
        <Task>
            <Code Type="Fragment" Language="cs">
                <![CDATA[
                    var xUnitFileName = XUnitFileName ?? "xunit.core.dll";
                    var testsSearchPattern = TestsSearchPattern ?? "*.Tests.dll";
                
                    // get all the directories containing xUnit dlls
                    var directories = System.IO.Directory.GetFiles
                                      (Path, xUnitFileName, System.IO.SearchOption.AllDirectories)
                        .Select(file => System.IO.Path.GetDirectoryName(file));

                    var assembliesList = new List<string>();

                    foreach(string directory in directories)
                    {
                        // get all test dlls from the given paths
                        assembliesList.AddRange(System.IO.Directory.GetFiles
                         (directory, testsSearchPattern, System.IO.SearchOption.TopDirectoryOnly));
                    }

                    Assemblies = assembliesList.ToArray();
                ]]>
            </Code>
        </Task>
    </UsingTask>

    <Target Name="Test">
        <GetAssemblies Path="$(BuildRoot).">
            <Output PropertyName="TestAssemblies" TaskParameter="Assemblies"/>
        </GetAssemblies>
        <xunit Assemblies="$(TestAssemblies)" />
    </Target>
</Project>