1.maven-surefire-plugin是个什么鬼?
如果你执行过mvn test
或者执行其他maven命令时跑了测试用例,你就已经用过maven-surefire-plugin
了。maven-surefire-plugin
是maven里执行测试用例的插件,不显示配置就会用默认配置。这个插件的surefire:test
命令会默认绑定maven执行的test
阶段。
maven的生命周期有哪些阶段?
[validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes,
test
, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy]
2.maven-surefire-plugin的使用
如果说maven已经有了maven-surefire-plugin的默认配置,我们还有必要了解maven-surefire-plugin的配置么?答案是肯定的。虽说maven-surefire-plugin有默认配置,但是当需要修改一些测试执行的策略时,就有必要我们去重新配置这个插件了。
2.1.配置JUnit
2.1.1.插件自动匹配
最简单的配置方式就不配置或者是只声明插件。
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
</plugin>
- 1
- 2
- 3
- 4
- 5
这个时候maven-surefire-plugin会按照如下逻辑去寻找JUnit的版本并执行测试用例。
if the JUnit version in the project >= 4.7 and the parallel attribute has ANY value
use junit47 provider
if JUnit >= 4.0 is present
use junit4 provider
else
use junit3.8.1
- 1
- 2
- 3
- 4
- 5
- 6
2.1.2.插件手动匹配
当然,如果你明确用的是JUnit4.7及以上版本,可以明确声明:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>2.19</version>
</dependency>
</dependencies>
</plugin>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
JUnit4.0(含)到JUnit4.7(不含)的版本,这样声明:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit4</artifactId>
<version>2.19</version>
</dependency>
</dependencies>
</plugin>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
JUnit3.8(含)到JUnit4.0(不含)的版本,这样声明:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit3</artifactId>
<version>2.19</version>
</dependency>
</dependencies>
</plugin>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
JUnit3.8以下的版本surefire不支持。建议大家用最新的JUnit版本,目前是4.12.
<dependencies>
[...]
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
[...]
</dependencies>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
本文的例子我们用的Junit4.12.
2.2.准备测试用例
我们现在准备两个类,一个被测试的类,一个测试用例.目录结构如下
现在我们准备一个简单的类.
package com.qyf404.learn.maven;
- 1
- 2
- 1