问题描述

环境:SpringBoot 2.2.5

包管理工具:Maven

最开始引入的测试包是org.junit.test,属于JUnit4,工程package时会自动执行单元测试,后来了解到JUnit5一些很好的特性,打算用JUnit5替代JUnit4。SpringBoot 2.2.5提供了两套API,既有JUnit4也有JUnit5,所以我以为将包换成org.junit.jupiter.api.Test,对应的方法换成JUnit5就可以。但是换完之后发现每次package都没有执行测试用例,始终是:

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

官网对JUnit的定义:JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage

SpringBoot 2.2.5中引入的JUnit如下图:JUnit Vintage + JUnit Jupiter + JUnit Platform,缺少JUnit Platform,官网给JUnit Platform的定义:

The JUnit Platform serves as a foundation for launching testing frameworks on the JVM. It also defines the TestEngine API for developing a testing framework that runs on the platform. Furthermore, the platform provides a Console Launcher to launch the platform from the command line and a JUnit 4 based Runner for running any TestEngine on the platform in a JUnit 4 based environment. First-class support for the JUnit Platform also exists in popular IDEs and build tools.

大概意思就是JUnit Platform是测试框架启动的基础。所以没有JUnit Platform可以正常使用JUnit的API,但是不能正常启动。由于没有启动器,IDE应该默认用的JUnit启动器,但是我的API引入的又是JUnit5的接口,所以我的maven打包时扫描不到我的单元测试,也就出现了上面说的情况。
在这里插入图片描述

下图是SpringBoot 2.4.2的依赖关系图,可以看到这个版本的引入了Junit Jupiter和Junit Platform,而没有引入JUnit Vintage,但是也可以正常使用。JUnit Vintage的定义:

JUnit Vintage provides a TestEngine for running JUnit 3 and JUnit 4 based tests on the platform.

意思是Vintage是用来兼容JUnit3和JUnit4的,SpringBoot 2.4.2选择不兼容3和4,只使用JUnit5,所以在这个版本中要使用JUnit4就需要自己引入依赖了。

在这里插入图片描述

解决方案

SpringBoot 2.2.5要使用Junit5来执行单元测试,需要:

  1. 手动引入JUnit PlatForm依赖
<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-runner</artifactId>
	<version>1.5.1</version>
</dependency>
  1. 在单元测试类上加上@RunWith(JUnitPlatform.class),最新版本不用加,具体哪一个版本不太清楚
@RunWith(JUnitPlatform.class)
public class Test{
    
}

遗留问题

我在SpringBoot 2.2.5中的单元测试并没有加public关键字,但是可以正常跑。在SpringBoot 2.4.2中必须在测试类和方法上都声明为public测试才能正常执行。JunitPlatform源码里的注释:

 /* Note, however, that any test class run with this runner must be {@code public} in order to be picked up byIDEs and build tools.*/

所以,加上肯定不会有错,但是为什么我还没搞清楚。

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐