赞
踩
首先确认Intellij IDEA版本,2017.3.5版本之前都不支持Junit5,2017.3.5版本开始就支持Junit5了。
2018.2.5版本之前,使用快捷键Alt + Insert,只能选择JUnit Test->JUnit 4,
2018.3.3版本,就可以选择JUnit Test->JUnit 5了。
2018.2.5使用JUnit 5需要按快捷键Ctrl + Shift + T,进行选择。
先介绍一下Intellij IDEA安装JUnit插件方法:
点击File,选择Settings,点击Plugins,输入JUnit,
IDEA自带的JUnit插件和JUnitGeneratorV2.0插件都要勾选上,若只勾选JUnit可能导致无法自动生成测试文件,
若只勾选JUnitGenerator V2.0可能导致生成的测试文件无法运行。
Spring Boot 在 2.* 版本之后,默认只能使用JUnit5 来进行单元测试。如果你还想使用JUnit4 进行单元测试,需要手动配置,方法如下:
在pom.xml文件中添加:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
如果测试类的引入爆红,
import org.junit.Test;
import org.junit.Before;
import org.junit.After;
还需要手动添加JUnit4的依赖:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope><!-- 如果编译不通过,去掉这行即可 -->
</dependency>
如果配置文件是这样的:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
需要删除
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
如果使用JUnit5 来进行单元测试,在配置文件中添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
手动添加JUnit5的依赖:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.5.2</version>
<scope>test</scope><!-- 如果编译不通过,去掉这行即可 -->
</dependency>
或者:
<!-- Junit 5 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
注意:
junit-vintage-engine 和 junit-jupiter-engine 有什么不同
junit-vintage-engine 是 JUnit 4 中使用的测试引擎。
junit-jupiter-engine 是 JUnit 5 中使用的测试引擎。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。