Spring Boot 2.x 实践记:@SpringBootTest

目录

  • @SpringBootTest
  • 用@SpringBootTest集成测试
  • 用@SpringBootTest单元测试
  • 小结

TL;DR

Spring Boot 中做测试,默认使用 @SpringBootTest 注解,今天我们就来快速学习如何进行单元测试或集成测试。

1. @SpringBootTest

运行Sprng Boot 测试,只需要在测试类上指定 @SpringBootTest,它的类声明如下:
在这里插入图片描述
写Spring Boot的测试类时一定要注意:启动类的位置,因为 @SpringBootTest 会优先搜索当前目录及其子目录。

在老的 spring-test 中,我们通常使用@ContextConfiguration(classes=…​)注解来获得测试时的上下文Context信息,而在Spring Boot Test 中都是通过@SpringBootTest来自动完成的。

2. 用@SpringBootTest集成测试

其实,@SpringBootTest 的原理就是模仿由 Spring Boot 框架提供的运行时上下文,比如:

  • 根据包结构决定要扫描哪些内容
  • 从预定义的位置加载外部配置
  • 可选地运行自动配置的启动器等

所以编写的测试类其实很简单,如下代码示例:

@SpringBootTest
public class SpringBootDemoApplicationTests 
{   
    //---- tests -----
}

3. 用@SpringBootTest单元测试

3.1. classes 属性

除了加载所有的服务外,我们在很多时候希望能更精准的进行指定服务的测试,这时我们就会用到classes属性,用来指定用于加载 ApplicationContext 里的特定类(注意:需要是实现类,而不是接口类)。

@SpringBootTest(classes = {TestManDaoImpl.class,TestManServiceImpl.class})
public class SpringBootDemoApplicationTests 
{   
    @Resource
    private TestManService testManService;
    
    //---- tests -----
}

3.2. *…Test 相关注解

除了 @SpringBootTest 注解外,Spring Boot 还提供了很多特定注解来帮助我们快速完成测试。

不过,这些注解可能会禁用自动配置,使用时需要仔细阅读说明。

更多详情,参看:Spring Boot Features Testing

4. 结论

到此,我们已经能使用@SpringBootTest注解来对Spring Boot应用编写集成测试或单元测试。

欢迎留言。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值