MSBuild的目标是运行所有测试,即使有些测试失败

时间:2011-01-14 01:42:27

标签: testing msbuild nunit

我有一个MSBuild脚本,使用控制台运行程序运行NUnit单元测试。有多个测试项目,如果可能的话,我想将它们作为单独的MSBuild目标。如果测试失败,我希望整体构建失败。但是,我想继续运行所有测试,即使其中一些测试失败。

如果我设置ContinueOnError="true",那么无论测试结果如何,构建都会成功。如果我将其保留为false,则在第一个失败的测试项目之后构建停止。

1 个答案:

答案 0 :(得分:7)

执行此操作的一种方法是为NUnit任务设置ContinueOnError="true",但从NUnit进程中获取退出代码。如果退出代码永远!= 0,则创建一个新属性,稍后您可以在脚本中使用该属性来使构建失败。

示例:

<Project DefaultTargets="Test"
         xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <UnitTests Include="test1">
      <Error>true</Error>
    </UnitTests>
    <UnitTests Include="test2">
      <Error>false</Error>
    </UnitTests>
    <UnitTests Include="test3">
      <Error>true</Error>
    </UnitTests>
    <UnitTests Include="test4">
      <Error>false</Error>
    </UnitTests>
    <UnitTests Include="test5">
      <Error>false</Error>
    </UnitTests>
  </ItemGroup>

  <Target Name="Test" DependsOnTargets="RunTests">
    <!--Fail the build.  This runs after the RunTests target has completed-->
    <!--If condition passes it will out put the test assemblies that failed-->
    <Error Condition="$(FailBuild) == 'True'"
           Text="Tests that failed: @(FailedTests) "/>
  </Target>

  <Target Name="RunTests" Inputs="@(UnitTests)" Outputs="%(UnitTests.identity)">
    <!--Call NUnit here-->
    <Exec Command="if %(UnitTests.Error) == true exit 1" ContinueOnError="true">
      <!--Grab the exit code of the NUnit process-->
      <Output TaskParameter="exitcode" PropertyName="ExitCode" />
    </Exec>

    <!--Just a test message-->
    <Message Text="%(UnitTests.identity)'s exit code: $(ExitCode)"/>

    <PropertyGroup>
      <!--Create the FailedBuild property if ExitCode != 0 and set it to True-->
      <!--This will be used later on to fail the build-->
      <FailBuild Condition="$(ExitCode) != 0">True</FailBuild>
    </PropertyGroup>

    <ItemGroup>
      <!--Keep a running list of the test assemblies that have failed-->
      <FailedTests Condition="$(ExitCode) != 0"
                   Include="%(UnitTests.identity)" />
    </ItemGroup>
  </Target>

</Project>