测试学习笔记1:@SpringbootTest测试注解详解

@SpringBootTest是一个用于在springboot应用程序中启动完整应用的测试环境注解。它主要用于集成测试,可以启动一个嵌入式的数据库,加载完整的spring上下文,并自动装配测试类的ApplicationContext。

以下是@SpringBootTest的关键特性:

  • 自动配置上下文环境:@SpringBootTest能够根据测试类所在的包扫描应用程序组件,并自动配置一个完整的Spring上下文;
  • 自动配置Mock服务:@SpringBootTest自动为应用程序中的服务提供mock实现,这使得能够不依赖真实服务的情况下进行测试;
  • 自动配置嵌入式数据库:@SpringBootTest自动配置一个嵌入式数据库,如:H2、HSQL或Derby,者能够使我们在不依赖外部数据库的情况下进行测试;
  • 自动配置切面或拦截器:@SpringBootTest自动应用一系列的切面或拦截器,以便在在测试期间记录或验证应用程序的行为。

下面的简单案例展示如何通过@SpringBootTest注解完成简单的单元测试:

定义一个service类:

@Service
public class MysqlServiceImpl implements MysqlService {
   
    @Autowired
    private MysqlMapper mysqlMapper;

    @Override
    public List<World> getMysql() {
   
        return mysqlMapper.getMysql("田晓霞", "123456");
    }
}

定义一个单元测试类:

@SpringBootTest
public class MysqlServiceTest {
   
    @Autowired
    private MysqlServiceImpl mysqlService;
    @MockBean
    private MysqlMapper mysqlMapper;

    @Test
    public void getMysql() {
   
        World world = new World();
        world.password = "123";
        when(mysqlMapper.getMysql("田晓霞", "123456")).thenReturn(Lists.newArrayList(world));
        List<World> list = mysqlService.getMysql();
        Assertions.assertEquals(list.get(0).password, "123");
    }
}

在此案例中,spring boot会启动一个完整的spring应用上下文,并自动装配MysqlServiceTest类中所有的@Autowired类,通过@MockBean注解模拟真实需要的MysqlMapper实例对象,通过when、thenReturn模拟返回数据,避免调用真实的数据库实现。

GitHub地址:https://github.com/mingyang66/spring-parent

相关推荐

  1. 测试学习笔记1:@SpringbootTest测试注解详解

    2023-12-16 03:36:01       61 阅读
  2. Springboot中测试问题(@SpringbootTest

    2023-12-16 03:36:01       36 阅读
  3. 测试学习1

    2023-12-16 03:36:01       43 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-16 03:36:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-16 03:36:01       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-16 03:36:01       87 阅读
  4. Python语言-面向对象

    2023-12-16 03:36:01       96 阅读

热门阅读

  1. 一个简单的cmake模板(C++)

    2023-12-16 03:36:01       70 阅读
  2. Zabbix监控网站

    2023-12-16 03:36:01       53 阅读
  3. idea注释高亮提示

    2023-12-16 03:36:01       65 阅读
  4. 知识迁移加持下的自监督学习

    2023-12-16 03:36:01       61 阅读
  5. 第19节:Vue3 在模板中展开时的注意事项

    2023-12-16 03:36:01       61 阅读
  6. 使用Linux命令修改服务器时间及设置时区

    2023-12-16 03:36:01       62 阅读
  7. 【Python 千题 —— 基础篇】整数输入

    2023-12-16 03:36:01       60 阅读