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() {}
}

参考

相关推荐
用户214118326360213 分钟前
Claude Skills 实战指南:3 分钟搞定 PPT、海报与 Logo,AI 办公效率翻倍!
后端
想搞艺术的程序员28 分钟前
Go Error 全方位解析:原理、实践、扩展与封装
开发语言·后端·golang
程序定小飞2 小时前
基于springboot的web的音乐网站开发与设计
java·前端·数据库·vue.js·spring boot·后端·spring
舒一笑2 小时前
从手写周报到智能生成:PandaCoder如何让你的工作汇报效率提升10倍
后端·程序员·intellij idea
无名之辈J2 小时前
支付常犯错误
后端
武昌库里写JAVA2 小时前
element-ui 2.x 及 vxe-table 2.x 使用 css 定制主题
java·vue.js·spring boot·sql·学习
申阳2 小时前
Day 6:04. 基于Nuxt开发博客项目-LOGO生成以及ICON图标引入
前端·后端·程序员
硅胶人2 小时前
[prowlarr][radarr][sonarr][qBitorrent]套件打造家庭影音中心
后端
JavaGuide3 小时前
OPPO 后端校招面试,过于简单了!
java·后端
调试人生的显微镜3 小时前
如何查看手机使用记录?四种实用方法详解
后端