SpringBoot 单元测试不执行:maven-surefire-plugin 版本问题

发布时间 2023-08-03 09:43:29作者: kelelipeng

SpringBoot 单元测试不执行:maven-surefire-plugin 版本问题

 

问题现象

Spring Boot 项目,在编写单元测试时,使用了 JUnit 4.13.2 以上的版本。

为了让 Maven 能自动运行单元测试,需要引入 Maven Surefire 或 Maven Failsafe 插件。

项目中使用的 maven-surefire-plugin 版本号为 2.22.2,在通过 mvn clean package 打包编译时,没有执行单元测试。

在经过一系列的测试后,发现只有 2.21 及以下版本的 maven-surefire-plugin 可以正常运行单元测试。

解决方法

根据上面的分析,最直观的解决方法就是降低 maven-surefire-plugin 的版本号。

但作为一个程序开发人员,怎么能止步于此呢?

去看看 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

如果不使用默认方式去查找 JUnit 的包,我们可以通过手动置顶内置的依赖,比如:

1、如果是 JUnit4.7 及以上版本,可以明确声明:

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-surefire-plugin</artifactId>
	<version>2.22.2</version>
	<dependencies>
		<dependency>
			<groupId>org.apache.maven.surefire</groupId>
			<artifactId>surefire-junit4</artifactId>
			<version>2.22.2</version>
		</dependency>
	</dependencies>
</plugin>

***同时必须引用 junit4.12以上版本***
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

 

 

2、JUnit 4.0 (含) 到 JUnit4 .7 (不含) 的版本,这样声明:

org.apache.maven.plugins maven-surefire-plugin 2.22.2 org.apache.maven.surefire surefire-junit4 2.22.2 ```

3、JUnit 3.8 (含) 到 JUnit 4.0 (不含) 的版本,这样声明:

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-surefire-plugin</artifactId>
	<version>2.22.2</version>
	<dependencies>
		<dependency>
			<groupId>org.apache.maven.surefire</groupId>
			<artifactId>surefire-junit3</artifactId>
			<version>2.22.2</version>
		</dependency>
	</dependencies>
</plugin>

4、JUnit 3.8 以下的版本,啊哦,surefire 已经不支持这么低版本的 JUnit 了,赶紧升级下 JUnit 的版本吧。

参考资料:

学习Maven之Maven Surefire Plugin(JUnit篇)