spring环境下单元测试:
SpringBoot环境下单元测试:
一、SpringBoot2.4.0之后
二、2.2.0 < SpringBoot < 2.4.
三、SpringBoot2.2.0之前
最近写SpringBootTest单元测试时,加入@Test无法启动测试方法(我用的是SpringBoot2.2.0之前的版本),然后我根据错误提示找到了解决方法一,但我记得之前学习SpringBoot环境下单元测试不是这样做的,我就翻阅之前的资料,找到了解决方法二,然后我发现之前是不用加@RunWith(SpringRunner.class)的,此时我就不太理解了。之前只会使用,没碰到过什么问题,所以也没去研究过。什么情况下需要加@RunWith(SpringRunner.class),什么情况下不需要加?为了解决疑问,通过查阅资料,分享一下我的总结。
先说一下我上面的解决方法:
方法一:不加@RunWith,直接导入junit-jupiter坐标
方法二:添加注解@RunWith(SpringRunner.class)
总结一下什么情况下需要使用@RunWith(SpringRunner.class):
spring环境下单元测试:
使用@RunWith(SpringJUnit4ClassRunner.class)设置类运行器
使用@ContextConfiguration设置Spring环境对应的配置类或配置文件
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {
@Autowired
private BookService bookService;
@Test
public void testSave(){
bookService.save();
}
}
SpringBoot环境下单元测试:
一、SpringBoot2.4.0之后
1、SpringBoot2.4.0之后,spring-boot-starter-test默认仅支持JUnit5,去掉了兼容JUnit4引擎:org.junit.vintage:junit-vintage-engine,无需添加@RunWith(SpringRunner.class)
@SpringBootTest
class BookServiceTest {
@Autowired
private BookService bookService;
@Test
void save() {
bookService.save();
}
}
二、2.2.0 < SpringBoot < 2.4.0
2、2.2.0 < SpringBoot < 2.4.0,spring-boot-starter-test默认使用JUnit5,同时也兼容支持JUnit4,无需添加@RunWith(SpringRunner.class)
@SpringBootTest
class BookServiceTest {
@Autowired
private BookService bookService;
@Test
void save() {
bookService.save();
}
}
如果想只用Junit5,可以排除junit-vintage-engine,排除Junit4的干扰,JUnit4中使用的测试引擎是junit-vintage-engine,JUnit5中使用的测试引擎是junit-jupiter-engine
<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>
三、SpringBoot2.2.0之前
1.SpringBoot2.2.0之前,spring-boot-starter-test引入的是JUnit4,使用的测试引擎是junit-vintage-engine
详说一下上面的解决方法:
解决方法一:不加@RunWith,直接导入junit-jupiter坐标
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.9.1</version>
</dependency>
导入坐标后可以看到junit-jupiter-engine的测试引擎
解决方法二:添加注解@RunWith(SpringRunner.class) 推荐使用
如果使用SpringBoot2.2.0之前的版本,按照下面这样写就行了
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestConnection {
@Test
public void test() {
}
}
提示:测试类和方法需要改成public类型,不改的话测试方法无法启动
如果不加@RunWith,测试方法能正常启动,但是测试可能会失败,比如出现@Autowired无法注入等一些问题
看一下官方的说明
如果您使用的是JUnit4,请记得将@RunWith(SpringRunner.class)添加到测试方法中,否则注解将被忽略。如果您使用的是JUnit5,则无需添加等效的@ExtendWith(SpringExtension),因为@SpringBootTest和其他@…Test注解已经包含了这些注解。