Spring Boot 测试最佳实践

🧪 1. 测试分层策略 (Testing Strategy / Pyramid)

核心思想:多写单元测试,少写E2E测试
Core idea: More unit tests, fewer E2E tests

复制代码
        E2E Tests(少 / Few)
     Integration Tests(中 / Medium)
Unit Tests(多 / Many)

✅ 2. 单元测试最佳实践 (Unit Testing Best Practices)

👉 使用:JUnit + Mockito

✔ 原则 / Principles

  • 只测试一个类 (Test one class only)

  • Mock 外部依赖 (Mock dependencies)

  • 不连接数据库/网络 (No DB / network)


✔ 示例 / Example

复制代码
@ExtendWith(MockitoExtension.class)
class UserServiceTest {

    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService;

    @Test
    void shouldReturnUser_whenUserExists() {
        User user = new User(1L, "Neo");

        when(userRepository.findById(1L)).thenReturn(Optional.of(user));

        User result = userService.getUserById(1L);

        assertEquals("Neo", result.getName());
    }
}

💡 关键点 / Key Points

  • 使用 @Mock 模拟依赖

  • 使用 @InjectMocks 注入被测类

  • Use @Mock to isolate dependencies

  • Use @InjectMocks for target class


🔗 3. 集成测试最佳实践 (Integration Testing)

👉 使用:@SpringBootTest


✔ 原则 / Principles

  • 测试模块之间真实交互 (Test real interactions)

  • 可以连接数据库 (DB allowed)

  • 使用测试数据库 (Use test DB, e.g. H2)


✔ 示例 / Example

复制代码
@SpringBootTest
@Transactional
class UserServiceIntegrationTest {

    @Autowired
    private UserService userService;

    @Test
    void shouldSaveUser() {
        User user = new User(null, "Neo");

        User saved = userService.save(user);

        assertNotNull(saved.getId());
    }
}

💡 建议 / Tips

  • 使用 H2 内存数据库 (Use H2 in-memory DB)

  • 使用 @Transactional 自动回滚

  • Rollback after each test


🌐 4. Controller / API 测试 (Web Layer Testing)

👉 使用:@WebMvcTest + MockMvc


✔ 示例 / Example

复制代码
@WebMvcTest(UserController.class)
class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Test
    void shouldReturnUser() throws Exception {
        when(userService.getUserById(1L))
            .thenReturn(new User(1L, "Neo"));

        mockMvc.perform(get("/users/1"))
               .andExpect(status().isOk())
               .andExpect(jsonPath("$.name").value("Neo"));
    }
}

💡 关键点 / Key Points

  • 只加载 Web 层 (Load only web layer)

  • 使用 @MockBean 替代真实 Service

  • Use MockMvc to simulate HTTP calls


🧩 5. 数据库测试 (Repository Testing)

👉 使用:@DataJpaTest


✔ 示例 / Example

复制代码
@DataJpaTest
class UserRepositoryTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    void shouldFindByName() {
        userRepository.save(new User(null, "Neo"));

        Optional<User> user = userRepository.findByName("Neo");

        assertTrue(user.isPresent());
    }
}

💡 特点 / Features

  • 只加载 JPA 相关组件

  • Faster than full Spring context

  • 默认使用内存数据库


🔁 6. 回归测试策略 (Regression Strategy)

✔ 建议 / Recommendations

  • 每次提交运行单元测试

    Run unit tests on every commit

  • CI/CD 运行全部测试

    Run all tests in pipeline

  • 关键路径加 E2E

    Add E2E for critical flows


🚀 7. 测试命名规范 (Naming Convention)

👉 推荐格式 / Recommended format:

复制代码
should + ExpectedResult + when + Condition

示例 / Example

  • shouldReturnUser_whenUserExists

  • shouldThrowException_whenUserNotFound


⚠️ 8. 常见错误 (Common Mistakes)

❌ 写太多集成测试 → 慢

Too many integration tests → slow

❌ 单元测试依赖数据库

Unit test depends on DB

❌ 不做Mock

No mocking → not isolated

❌ 测试没有断言

No assertions


🧠 9. 最佳实践总结 (Final Summary)

类型 工具 用途
单元测试 JUnit + Mockito 快速、隔离
集成测试 @SpringBootTest 模块协作
Web测试 @WebMvcTest API层
数据库测试 @DataJpaTest JPA

💡 一句话总结 (One-line takeaway)

👉 80% 单元测试 + 15% 集成测试 + 5% E2E

👉 Focus on unit tests, use integration wisely

相关推荐
企业数字化笔记3 分钟前
AI工具参数很多怎么办?预设、表单校验、危险参数与配置审计
java·spring boot·python·音视频
牛奔24 分钟前
mise 管理多版本 Go 项目
开发语言·前端·chrome·后端·golang
huaweichenai37 分钟前
spring boot对接阿里短信
java·spring boot
马剑威(威哥爱编程)1 小时前
【AI全栈后端12-08】Spring Boot 用 MCP 统一接入内部系统:让 AI 接一次,全公司复用
java·人工智能·spring boot
顽疲1 小时前
从零用 Java 实现小红书 SpringBoot Vue UniApp(23)笔记话题多对多:一条笔记进多个话题池
java·vue.js·spring boot
打工仔折腾 AI1 小时前
FaceFusion本地换脸实战:Windows整合包、模型选择与遮罩调参记录
人工智能·windows·后端·python·深度学习·性能优化·ai agent 实战
做个文艺程序员1 小时前
MQ第02篇:RabbitMQ快速上手教程:AMQP模型详解+Spring Boot整合实战(附完整代码)
spring boot·消息队列·rabbitmq·java-rabbitmq·amqp
RuoyiOffice1 小时前
SpringBoot3 企业定时结算架构:考勤日结、合同到期、库存预警与财务结转如何可靠执行
spring boot·xxl-job·定时任务·分布式任务·spring boot 3·幂等设计·ruoyi office
Nebula_g2 小时前
JavaSE拓展:工具类Executors
java·开发语言·后端·spring·基础·javase
弈栈录2 小时前
Java 后端高并发设计:线程池、限流、熔断与降级
后端·架构