建立 Spring Boot 单元测试方法一般依赖于 JUnit4 或 JUnit5 框架。
在高版本的 Spring Boot 中,一般默认用的是 JUnit5。此时通过添加 @SpringBootTest 注解,即可成功注入相关的 bean 对象,并进行测试。
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
class testClass {@Autowiredprivate LimitServiceImpl limitServiceImpl;@Testpublic void test() {}
}
如果使用的是 JUnit4,则需要额外添加 @Runwith(SpringRunner.class) 注解,用于声明测试的环境为 Spring 环境。
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 {@Autowiredprivate LimitServiceImpl limitServiceImpl;@Testpublic void test() {}
}
参考
- 何时使用@RunWith
- Spring Boot 单元测试基本使用,不污染数据库操作
- Spring Boot 单元测试,通过 MockMvc 模拟 HTTP 请求