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

参考

相关推荐
小满zs9 小时前
Go语言第十七章(反射)
后端·go
小满zs9 小时前
Go语言第十五章(JSON序列化)
后端·go
小满zs9 小时前
Go语言第十六章(自定义类型)
后端·go
yz_aiks10 小时前
Spring AI 2.1 ChatMemory 已过时用什么替代:迁移到 Session Memory 实战(JDBC 存储与会话压缩)
java·spring boot·大模型·ai agent·spring ai
金銀銅鐵10 小时前
[Java] 用 GUI 展示 EnumMap 增删键值对时的内部变化
java·后端·ai编程
学长毕设10 小时前
基于SpringBoot的上门洗车服务系统设计与实现
java·spring boot·后端
小溪学编程13 小时前
Spring @Bean 与 @Component 注解的区别详解
java·后端·spring
IT_陈寒13 小时前
Python的列表推导式用不好真的会爆内存你知道吗
前端·人工智能·后端
摸爬滚打的小李15 小时前
TomCat
后端
itmigrate15 小时前
Rust 里的所有权误区:不是不写 clone 就叫高性能
开发语言·后端·rust