无条件地在ant中执行任务?

Kri*_*den 6 java ant unit-testing

我正在尝试定义在目标完成执行时发出(使用echo)消息的任务,无论该目标是否成功.具体来说,目标执行一个任务来运行一些单元测试,我想发出一条消息,指出结果的可用位置:

<target name="mytarget">
  <testng outputDir="${results}" ...>
    ...
  </testng>
  <echo>Tests complete.  Results available in ${results}</echo>
</target>
Run Code Online (Sandbox Code Playgroud)

不幸的是,如果测试失败,则任务失败并且执行中止.因此,只有在测试通过时才输出消息 - 与我想要的相反.我知道我可以将任务放在任务之前,但这会让用户更容易错过这条消息.我正在尝试做什么?

更新:事实证明我是愚蠢的.我的<testng>任务中有haltOnFailure ="true",这解释了我所看到的行为.现在的问题是,将此设置为false会导致整个ant构建成功,即使测试失败,这也不是我想要的.以下使用该任务的答案看起来可能是我想要的......

Jay*_*Jay 5

根据Ant文档,如果testng任务失败,有两个属性可以控制构建过程是否停止:

haltonfailure - 如果在测试运行期间发生故障,则停止构建过程.默认为false.

haltonskipped - 如果至少跳过测试,则停止构建过程.默认为false.

如果您正在设置此属性,我无法从片段中分辨出来.如果当前设置为true,可能值得尝试将haltonfailure显式设置为false.

此外,假设您在Ant中使用<exec>功能,还有类似的属性来控制执行的命令失败时会发生什么:

failonerror - 如果命令退出并返回代码信号失败,则停止构建过程.默认为false.

failifexecutionfails - 如果我们无法启动程序,请停止构建.默认为true.

根据帖子中的部分代码片段无法分辨,但我的猜测是最可能的罪魁祸首是failonerrorhaltonfailure设置为true.


小智 5

您可以像这样使用try-catch块:

<target name="myTarget">
    <trycatch property="foo" reference="bar">
        <try>
            <testing outputdir="${results}" ...>
                ...
            </testing>
        </try>

        <catch>
            <echo>Test failed</echo>
        </catch>

        <finally>
            <echo>Tests complete.  Results available in ${results}</echo>
        </finally>
    </trycatch>
</target>
Run Code Online (Sandbox Code Playgroud)


Ale*_*x B 4

问题的解决方案是将与testng 任务的属性failureProperty结合使用,如下所示:haltOnFailure

<target name="mytarget">
  <testng outputDir="${results}" failureProperty="tests.failed" haltOnFailure="false" ...>
    ...
  </testng>
  <echo>Tests complete.  Results available in ${results}</echo>
</target>
Run Code Online (Sandbox Code Playgroud)

然后,当您希望构建失败时,您可以添加如下 ant 代码:

<target name="doSomethingIfTestsWereSuccessful" unless="tests.failed">
   ...
</target>

<target name="doSomethingIfTestsFailed" if="tests.failed">
   ...
   <fail message="Tests Failed" />
</target>
Run Code Online (Sandbox Code Playgroud)

然后,您可以在您希望 ant 构建失败的地方调用 doSomethingIfTestsFailed。