Spring Boot 单元测试什么时候需要添加 @RunWith

建立 Spring Boot 单元测试方法一般依赖于 JUnit4 或 JUnit5 框架。

在高版本的 Spring Boot 中,一般默认用的是 JUnit5。此时通过添加 @SpringBootTest 注解,即可成功注入相关的 bean 对象,并进行测试。

java 复制代码
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class testClass {
	@Autowired
	private LimitServiceImpl limitServiceImpl;

	@Test
	public void test() {}
}

如果使用的是 JUnit4,则需要额外添加 @Runwith(SpringRunner.class) 注解,用于声明测试的环境为 Spring 环境。

java 复制代码
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
class testClass {
	@Autowired
	private LimitServiceImpl limitServiceImpl;

	@Test
	public void test() {}
}

参考

相关推荐
阑梦清川20 小时前
AI编程实战记录贴2/100,关于Github提交代码失败的思考
后端
兮动人20 小时前
spring boot2升级boot3指南
后端
哈喽姥爷20 小时前
Spring Boot--yml配置信息书写和获取
java·数据库·spring boot·mybatis
郭京京20 小时前
goweb模板语法html/template
后端·go
乐神嘎嘎嘎20 小时前
接口测试面试题
后端
AAA修煤气灶刘哥20 小时前
ES数据同步大乱斗:同步双写 vs MQ异步,谁才是王者?
分布式·后端·elasticsearch
武昌库里写JAVA20 小时前
Java设计模式中的几种常用设计模式
vue.js·spring boot·sql·layui·课程设计
Yvonne爱编码21 小时前
后端编程开发路径:从入门到精通的系统性探索
java·前端·后端·python·sql·go
Q_Q19632884751 天前
python+springboot大学生心理测评与分析系统 心理问卷测试 自动评分分析 可视化反馈系统
开发语言·spring boot·python·django·flask·node.js·php