Showing posts with label xUnit. Show all posts
Showing posts with label xUnit. Show all posts

Friday, May 22, 2015

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 have 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>