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

时间:2020-03-06 14:40:25  来源:igfitidea点击:

我试图定义一个任务,该任务在目标完成执行时发出(使用echo)消息,而不管该目标是否成功。具体来说,目标执行任务以运行一些单元测试,并且我想发出一条消息,指示可在何处获得结果:

<target name="mytarget">
  <testng outputDir="${results}" ...>
    ...
  </testng>
  <echo>Tests complete.  Results available in ${results}</echo>
</target>

不幸的是,如果测试失败,任务将失败并且执行将中止。因此,仅当测试通过与我想要的相反时,才输出消息。我知道我可以将任务放在任务之前,但这将使用户更容易错过此消息。我想做的事可能吗?

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

解决方案

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

haltonfailure - Stop the build process
  if a failure has occurred during the
  test run.  Defaults to false.  
  
  haltonskipped - Stop the build process
  if there is at least on skipped test. 
  Default to false.

我无法从代码段中得知我们是否设置了此属性。如果当前将haltonfailure设置为true,则可能值得尝试将其设置为false。

此外,假设我们在Ant中使用<exec>功能,则可以使用类似的属性来控制如果执行的命令失败将发生的情况:

failonerror - Stop the buildprocess if the command exits with a return code 
  signaling failure. Defaults to false.
  
  failifexecutionfails - Stop the build if we can't start the program. 
  Defaults to true.

无法根据我们帖子中的部分代码片段来判断,但我猜测是最可能的罪魁祸首是将failonerror或者haltonfailure设置为true。

我们可以使用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>

尽管在示例中显示了一个名为" testng"的虚假任务,但我假设我们正在使用junit目标。

在这种情况下,我们看到这些结果很奇怪,因为默认情况下junit目标不会在测试失败时中止执行。

实际上,有一种方法可以通过使用halt属性来告诉蚂蚁在junit失败或者错误时停止构建。 haltonfailure:

<target name="junit" depends="junitcompile">
    <junit printsummary="withOutAndErr" fork="yes" haltonfailure="yes">

但是,默认情况下会将haltonfailure和haltonerror都设置为off。我想我们可以检查构建文件,以查看是否已设置了这些标志中的任何一个。它们甚至可以全局设置,因此我们可以尝试的一件事是在任务中将其显式设置为" no",以确保在全局范围内进行设置时将其覆盖。

http://ant.apache.org/manual/Tasks/junit.html

你能分担testng任务吗?如果是,那么我们可能想要使用该功能,以便testng任务将在其他JVM上运行。

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

<target name="mytarget">
  <testng outputDir="${results}" failureProperty="tests.failed" haltOnFailure="false" ...>
    ...
  </testng>
  <echo>Tests complete.  Results available in ${results}</echo>
</target>

然后,在其他地方,当我们希望构建失败时,可以添加如下所示的ant代码:

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

<target name="doSomethingIfTestsFailed" if="tests.failed">
   ...
   <fail message="Tests Failed" />
</target>

然后,我们可以在希望蚂蚁构建失败的地方调用doSomethingIfTestsFailed。