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-junit47</artifactId>
			<version>2.22.2</version>
		</dependency>
	</dependencies>
</plugin>

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篇)


版权声明

作者:瘦风(https://healchow.com)

出处:博客园-瘦风的南墙(https://www.cnblogs.com/shoufeng)

感谢阅读,公众号 「瘦风的南墙」 ,手机端阅读更佳,还有其他福利和心得输出,欢迎扫码关注🤝

本文版权归博主所有,欢迎转载,但 [必须在页面明显位置标明原文链接],否则博主保留追究相关人士法律责任的权利。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章