Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute an Ant command if a task fails?

Tags:

java

ant

Suppose I have some Ant task - say javac or junit - if either task fails, I want to execute a task, but if they succeed I don't.

Any idea how to do this?

like image 625
tomjen Avatar asked Jun 19 '09 11:06

tomjen


1 Answers

In your junit target, for example, you can set the failureProperty:

<target name="junit" depends="compile-tests" description="Runs JUnit tests">
    <mkdir dir="${junit.report}"/>
    <junit printsummary="true" failureProperty="test.failed">
        <classpath refid="test.classpath"/>
        <formatter type="xml"/>
        <test name="${test.class}" todir="${junit.report}" if="test.class"/>
        <batchtest fork="true" todir="${junit.report}" unless="test.class">
            <fileset dir="${test.src.dir}">
                <include name="**/*Test.java"/>
                <exclude name="**/AllTests.java"/>
            </fileset>
        </batchtest>
    </junit>
</target>

Then, create a target that only runs if the test.failed property is set, but fails at the end:

<target name="otherStuff" if="test.failed">
    <echo message="I'm here. Now what?"/>
    <fail message="JUnit test or tests failed."/>
</target>

Finally, tie them together:

<target name="test" depends="junit,otherStuff"/>

Then just call the test target to run your JUnit tests. The junit target will run. If it fails (failure or error) the test.failed property will be set, and the body of the otherStuff target will execute.

The javac task supports failonerror and errorProperty attributes, which can be used to get similar behavior.

like image 52
Gene Gotimer Avatar answered Oct 19 '22 10:10

Gene Gotimer