当前位置: 首页 > news >正文

Spring Boot测试类的使用参考

Spring Boot测试类的使用参考

1. 集成测试概述

集成测试是在完整的Spring应用上下文中测试应用组件之间的交互。与单元测试不同,集成测试会启动Spring容器并加载所有配置的Bean。

2. 依赖配置

2.1 Maven依赖

<!-- Spring Boot测试核心依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- 如果需要测试Web接口,需添加此依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><scope>test</scope></dependency>

2.2 Gradle依赖

// Spring Boot测试核心依赖 testImplementation 'org.springframework.boot:spring-boot-starter-test' // Web接口测试依赖 testImplementation 'org.springframework.boot:spring-boot-starter-web'

3. 核心注解使用

3.1 @SpringBootTest注解

@SpringBootTest是Spring Boot集成测试的核心注解,用于启动完整的Spring应用上下文。

基础使用方式
@SpringBootTestpublicclassMyIntegrationTest{// 测试代码}
什么时候需要指定启动类?

在以下情况下需要在@SpringBootTest中指定classes属性:

  1. 多模块项目:测试类与Spring Boot启动类不在同一模块中
  2. 启动类不在默认包结构:测试类无法自动扫描到启动类
  3. 自定义配置:需要使用特定的配置类启动测试
// 示例:指定启动类@SpringBootTest(classes=MyApplication.class)publicclassMyIntegrationTest{// 测试代码}

4. 不同版本组合的使用案例

4.1 Spring Boot < 2.2 + JUnit 4

基础集成测试
importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)// 必须显式指定运行器@SpringBootTest(classes=MyApplication.class)// 指定启动类publicclassMyServiceTest{@AutowiredprivateMyServicemyService;// 注入实际的服务Bean@TestpublicvoidtestService(){// 调用实际的业务方法Stringresult=myService.process("test");// 断言结果assertEquals("expected",result);}}
Web接口集成测试
importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.test.context.junit4.SpringRunner;importorg.springframework.test.web.servlet.MockMvc;importstaticorg.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;importstaticorg.springframework.test.web.servlet.result.MockMvcResultMatchers.status;@RunWith(SpringRunner.class)@SpringBootTest(classes=MyApplication.class)@AutoConfigureMockMvc// 自动配置MockMvcpublicclassMyControllerTest{@AutowiredprivateMockMvcmockMvc;// 注入MockMvc实例@TestpublicvoidtestController()throwsException{mockMvc.perform(get("/api/test"))// 模拟HTTP请求.andExpect(status().isOk());// 验证响应状态}}

4.2 Spring Boot >= 2.2 + JUnit 5

基础集成测试
importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;@SpringBootTest(classes=MyApplication.class)// 指定启动类publicclassMyServiceTest{@AutowiredprivateMyServicemyService;// 注入实际的服务Bean@TestpublicvoidtestService(){// 调用实际的业务方法Stringresult=myService.process("test");// 断言结果assertEquals("expected",result);}}
Web接口集成测试
importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.test.web.servlet.MockMvc;importstaticorg.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;importstaticorg.springframework.test.web.servlet.result.MockMvcResultMatchers.status;@SpringBootTest(classes=MyApplication.class)@AutoConfigureMockMvc// 自动配置MockMvcpublicclassMyControllerTest{@AutowiredprivateMockMvcmockMvc;// 注入MockMvc实例@TestpublicvoidtestController()throwsException{mockMvc.perform(get("/api/test"))// 模拟HTTP请求.andExpect(status().isOk());// 验证响应状态}}

4.3 不指定启动类的情况

当测试类与Spring Boot启动类在同一模块且在同一包结构下时,可以不指定启动类:

// MyApplication.java 位于 com.example 包packagecom.example;@SpringBootApplicationpublicclassMyApplication{publicstaticvoidmain(String[]args){SpringApplication.run(MyApplication.class,args);}}// MyIntegrationTest.java 也位于 com.example 包packagecom.example;@SpringBootTest// 无需指定classes属性publicclassMyIntegrationTest{// 测试代码}

5. 常见集成测试场景

5.1 数据库集成测试

importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.transaction.annotation.Transactional;@SpringBootTest(classes=MyApplication.class)@Transactional// 测试后自动回滚数据库操作publicclassMyRepositoryTest{@AutowiredprivateMyRepositoryrepository;// 注入实际的Repository@TestpublicvoidtestRepository(){// 执行数据库操作MyEntityentity=newMyEntity();entity.setName("test");MyEntitysavedEntity=repository.save(entity);// 验证结果assertNotNull(savedEntity.getId());assertEquals("test",savedEntity.getName());}}

5.2 外部服务集成测试

importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;@SpringBootTest(classes=MyApplication.class)publicclassMyExternalServiceTest{@AutowiredprivateExternalApiServiceexternalApiService;// 注入调用外部API的服务@TestpublicvoidtestExternalApi(){// 调用外部APIStringresult=externalApiService.callExternalApi("test");// 验证结果assertNotNull(result);}}

6. 版本兼容性总结

Spring Boot版本JUnit版本核心注解是否需要指定启动类
< 2.24@RunWith(SpringRunner.class) @SpringBootTest多模块或非默认包结构时需要
>= 2.25@SpringBootTest多模块或非默认包结构时需要

7. 最佳实践

  1. 最小化测试范围:虽然是集成测试,也应尽量减少测试类之间的依赖
  2. 使用@Transactional:对于数据库测试,使用@Transactional确保测试后数据回滚
  3. 合理指定启动类:仅在必要时指定classes属性,避免硬编码
  4. 分离测试环境配置:使用不同的配置文件(如application-test.yml)配置测试环境
  5. 使用切片测试:对于大型应用,可以使用@WebMvcTest、@DataJpaTest等切片测试注解,在不启动完整上下文的情况下进行集成测试
http://www.jsqmd.com/news/206425/

相关文章:

  • 有监督学习神经网络改造为无监督学习的PyTorch可微分优化实现
  • 0101__WiX Toolset 安装包制作入门教程(目录篇)
  • 高通开源驱动ath12k已正式支持QCC2072
  • 宇信科技以金融科技前沿探索 获评《财经》新媒体2025“新奖”——“未来场景定义者”
  • 1024编程——让我们的孩子对话未来
  • 电力行业气体安全监测指南:气体检测仪的应用方案
  • unibest+uview-plus,tabbar icon不展示
  • 学霸同款2026 AI论文工具TOP9:本科生毕业论文写作全解析
  • vue基于spring boot的校园高校毕业生房屋租赁 预约看房 合同 报修应用和研究
  • vue 表格 vxe-table 如何实现透视表拖拽对数据进行分组汇总,金额合计、平均值等
  • 语言模型在复杂系统风险评估与金融市场稳定性分析中的应用
  • ARM处理器芯片之UEFI
  • 行业透视:云服务器如何重塑各行各业
  • vue基于Spring Boot的高校教师考勤科研培训管理系统设计与实现应用和研究
  • 学长亲荐2026TOP8AI论文平台:本科生毕业论文写作全测评
  • 展望未来:云服务器的下一个十年
  • Linux who指令查询和显示当前登录系统的用户信息
  • 大疆无人机常见故障提示及应对指南
  • LINUX modprobe 智能加载和卸载内核模块
  • 英伟达的AI芯片架构演进的三个阶段
  • vue基于spring boot的乡村民宿预订周边旅游管理系统应用和研究
  • vue基于Spring Boot的协同过滤算法的快捷酒店预定管理系统设计与开发应用和研究
  • 【私域商城系统】
  • 从HTML注入到CSRF:一次漏洞组合拳实战
  • vue基于Spring Boot的实验室预约 设备耗材申请管理系统 学生 教师应用和研究
  • “数据不灭” 的技术底气
  • 2026必备!自考论文难题TOP10 AI论文平台深度测评
  • vue基于spring boot的宠物领养救助系统 宠物用品商城管理系统x26k3505应用和研究
  • 全链路高可用架构 —— 从基建到应用的立体防护
  • vue基于Spring Boot的小区停车位短租管理系统的设计与实现java 沙箱支付应用和研究