作为回报,您的问题提出了一个明显的问题,为什么不简单地使用 Maven 来运行 JUnit? surefire plugin 将执行在测试编译阶段编译到目标/测试类(通常是 src/test/java 的内容)中的任何测试(在测试阶段)。有一个 JavaWorld article 介绍了将 Junit 与 Maven 结合使用,您可能会觉得有帮助
假设您有正当理由使用 Ant 调用测试,您需要确保将 Ant 设置为在测试无效时失败。您可以通过配置JUnit task 来做到这一点。您可能希望设置的属性是 haltonerror 或 haltonfailure。或者,您可以在失败时设置一个属性,并使用 failureproperty 属性使 Ant 构建失败。
我提供了两个示例来演示导致 Maven 构建失败的 Ant 失败。第一个是直接调用失败任务,第二个是调用 build.xml 中的一个任务,方式与您所做的相同。
这个简单的例子表明 ant 失败会导致 Maven 构建失败:
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<phase>test</phase>
<configuration>
<tasks>
<fail message="Something wrong here."/>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
[INFO] [antrun:run {execution: default}]
[INFO] Executing tasks
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] An Ant BuildException has occured: Something wrong here.
扩展示例以使用 ant 调用:
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<phase>test</phase>
<configuration>
<tasks unless="maven.test.skip">
<ant antfile="${basedir}/build.xml" target="test">
<property name="build.compiler" value="extJavac" />
</ant>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
build.xml 为:
<?xml version="1.0"?>
<project name="test" default="test" basedir=".">
<target name="test">
<fail message="Something wrong here."/>
</target>
</project>
给出以下错误:
[INFO] [antrun:run {execution: default}]
[INFO] Executing tasks
test:
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] An Ant BuildException has occured: The following error occurred while executing this line:
C:\test\anttest\build.xml:4: Something wrong here.