既然你的项目已经有单元测试了,那么让它们运行起来吧。 你不必为了运行单元测试做什么特殊的事情,
test 阶段是 Maven 生命周期中常规的一部分。 当你运行 mvn
package 或者 mvn install 的时候你也运行了测试。 如果你想要运行到
test 阶段为止的所有生命周期阶段,运行 mvn test
。
$ mvn test
...
[INFO] [surefire:test]
[INFO] Surefire report directory: ~/examples/simple-weather/target/surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running org.sonatype.mavenbook.weather.yahoo.WeatherFormatterTest
0 INFO YahooParser - Creating XML Reader
177 INFO YahooParser - Parsing XML Response
239 INFO WeatherFormatter - Formatting Weather Data
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.547 sec
Running org.sonatype.mavenbook.weather.yahoo.YahooParserTest
475 INFO YahooParser - Creating XML Reader
483 INFO YahooParser - Parsing XML Response
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.018 sec
Results :
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
从命令行运行 mvn test 使 Maven 执行到
test 阶段为止的所有生命周期阶段。 Maven Surefire 插件有一个
test 目标,该目标被绑定在了 test 阶段。
test 目标执行项目中所有能在 src/test/java
找到的并且文件名与 **/Test*.java,
**/*Test.java 和
**/*TestCase.java 匹配的所有单元测试。 在本例中,你能看到 Surefire 插件的
test 目标执行了 WeatherFormatterTest
和 YahooParserTest 。 在 Maven Surefire 插件执行 JUnit
测试的时候,它同时也在 /data/hudson-temporal-data/hudson-orchestrator-home/workspace/Book-To-Production/content-zh/target/surefire-reports 目录下生成
XML 和常规文本报告。
如果你的测试失败了,你可以去查看这个目录,里面有你单元测试生成的异常堆栈信息和错误信息。
通常,你会开发一个带有很多失败单元测试的系统。
如果你正在实践测试驱动开发(TDD),你可能会使用测试失败来衡量你离项目完成有多远。
如果你有失败的单元测试,但你仍然希望产生构建输出,你就必须告诉 Maven 让它忽略测试失败。 当 Maven
遇到一个测试失败,它默认的行为是停止当前的构建。 如果你希望继续构建项目,即使 Surefire 插件遇到了失败的单元测试,你就需要设置
Surefire 的 testFailureIgnore 这个配置属性为
true。
Example 4.16. 忽略单元测试失败
<project>
[...]
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins>
</build>
[...]
</project>该插件文档 (http://maven.apache.org/plugins/maven-surefire-plugin/test-mojo.html) 说明,这个参数声明为一个表达式:
Example 4.17. 插件参数表达式
testFailureIgnore Set this to true to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on occasion.
* Type: boolean
* Required: No
* Expression: ${maven.test.failure.ignore}
这个表达式可以从命令行通过 -D 参数设置。
$ mvn test -Dmaven.test.failure.ignore=true
