2011-01-14 54 views
5

我有一個MSBuild腳本,使用控制檯運行器運行NUnit單元測試。有多個測試項目,如果可能的話,我想保留它們作爲單獨的MSBuild目標。如果測試失敗,我想整體構建失敗。但是,我想繼續運行所有測試,即使其中一些失敗。MSBuild的目標運行所有測試,即使有一些失敗

如果我設置了ContinueOnError="true"那麼無論測試結果如何,構建都會成功。如果我將它保留爲false,那麼在第一個失敗的測試項目之後,構建將停止。

回答

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> 
+0

僅供參考,該示例要求的msbuild 3.5運行。 –

相關問題