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

参考

相关推荐
人间凡尔赛17 分钟前
AI-Native 云原生架构:2026 年从容器编排到智能体编排的范式革命
后端·云原生·架构
吴声子夜歌27 分钟前
MongoDB 4.x——SpringBoot框架整合
数据库·spring boot·mongodb
IT_陈寒34 分钟前
Vue的响应式让我加班到凌晨3点,原来问题出在这
前端·人工智能·后端
卷无止境35 分钟前
提升 Python 代码健壮性的方法大盘点
后端·python
snow@li36 分钟前
Spring Boot:项目服务器完整部署教程(零基础可直接实操)
服务器·spring boot·后端
卷无止境1 小时前
Python 异常处理:从入门到工程实践
后端·python
AINative软件工程1 小时前
LLM 应用的熔断降级工程实践:Circuit Breaker 不只是重试的升级版
后端·llm·ai编程
程序员爱钓鱼1 小时前
Go 开发环境安装(Windows、macOS、Linux)
后端·面试·go
程序员爱钓鱼1 小时前
Rust String 与 &str 详解:字符串所有权、借用与转换
前端·后端·rust