目录
- @SpringBootTest
- 用@SpringBootTest集成测试
- 用@SpringBootTest单元测试
- 小结
TL;DR
在
1. @SpringBootTest
运行Sprng Boot 测试,只需要在测试类上指定

写Spring Boot的测试类时一定要注意:启动类的位置,因为 @SpringBootTest 会优先搜索当前目录及其子目录。
在老的 spring-test 中,我们通常使用
2. 用@SpringBootTest集成测试
其实,@SpringBootTest 的原理就是模仿由 Spring Boot 框架提供的运行时上下文,比如:
- 根据包结构决定要扫描哪些内容
- 从预定义的位置加载外部配置
- 可选地运行自动配置的启动器等
所以编写的测试类其实很简单,如下代码示例:
1 2 3 4 5 | @SpringBootTest public class SpringBootDemoApplicationTests { //---- tests ----- } |
3. 用@SpringBootTest单元测试
3.1. classes 属性
除了加载所有的服务外,我们在很多时候希望能更精准的进行指定服务的测试,这时我们就会用到classes属性,用来指定用于加载 ApplicationContext 里的特定类(注意:需要是实现类,而不是接口类)。
1 2 3 4 5 6 7 8 | @SpringBootTest(classes = {TestManDaoImpl.class,TestManServiceImpl.class}) public class SpringBootDemoApplicationTests { @Resource private TestManService testManService; //---- tests ----- } |
3.2. *…Test 相关注解
除了
不过,这些注解可能会禁用自动配置,使用时需要仔细阅读说明。
更多详情,参看:Spring Boot Features Testing
4. 结论
到此,我们已经能使用@SpringBootTest注解来对Spring Boot应用编写集成测试或单元测试。
欢迎留言。