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

参考

相关推荐
xixingzhe27 分钟前
SpringBoot DDD 实战入门文档
spring boot·spring·ddd
山岚的运维笔记36 分钟前
mysql 专业笔记 -- 第 17 章:连接:连接三个具有相同名称 ID 的表
运维·数据库·笔记·后端·学习·mysql·dba
遨翔在知识的海洋里39 分钟前
nest(3)- filter和Interceptor
后端
挽安6211 小时前
若依微服务 Nacos 2.x 控制台配置列表为空?一个 tenant_id 字段引发的血案
后端
周杰伦fans1 小时前
ASP.NET Core Identity 从入门到实战:常见问题与解决方案
后端·asp.net
n8n1 小时前
Spring AI 三层架构详解:ChatModel → ChatClient → Controller,同步调用 vs 流式调用(SSE)
后端
小傅哥1 小时前
Java + DDD,1:1 复刻 Deepseek Harness 项目
前端·后端·ai编程
Lambert2811 小时前
AgentScope Java 从零(03):Agent 的记性默认全开,我在第 50 轮翻了车
后端·aigc
积硅步致千里2 小时前
Word 里的 .wmf 其实是 EMF:一次 metafile 转 PNG 排障
前端·后端
爱读源码的大都督2 小时前
DeepSeek面试官问:生产RAG系统回答不准确,该如何定位和优化?这样回答,能让面试官当场给你Offer!
java·后端·python