321-frameworks-spring-boot-testing-unit-tests

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Spring Boot Unit Testing with Mockito

使用Mockito进行Spring Boot单元测试

Apply Spring Boot unit testing guidelines with Mockito.
What is covered in this Skill?
  • Pure unit tests: @ExtendWith(MockitoExtension.class), @Mock, @InjectMocks for @Service/@Component (no Spring context)
  • Slice tests: @WebMvcTest, @MockitoBean for controllers (Spring Boot 4.0.x — @MockBean removed)
  • @JsonTest for JSON serialization with correct JSON value assertions (extractingJsonPathStringValue, etc.)
  • Parameterized tests: @ParameterizedTest with @CsvSource or @MethodSource over copy-pasted methods
  • Java records for domain objects in tests
  • @TestConfiguration, @ActiveProfiles, @Primary fixed-clock beans for deterministic test setup
  • Modern mocking API: @MockitoBean / @MockitoSpyBean; @MockBean/@SpyBean are deprecated/removed in Boot 4.0.x
Scope: Apply recommendations based on the reference rules and good/bad code examples. For integration tests use @322-frameworks-spring-boot-testing-integration-tests.
遵循使用Mockito的Spring Boot单元测试指南。
本技能涵盖哪些内容?
  • 纯单元测试:使用@ExtendWith(MockitoExtension.class)、@Mock、@InjectMocks为@Service/@Component编写测试(无需Spring上下文)
  • 切片测试:使用@WebMvcTest、@MockitoBean为控制器编写测试(Spring Boot 4.0.x 版本中@MockBean已被移除)
  • @JsonTest:用于JSON序列化测试,包含正确的JSON值断言(如extractingJsonPathStringValue等)
  • 参数化测试:使用@ParameterizedTest搭配@CsvSource或@MethodSource,替代复制粘贴的方法
  • 测试中的Java records领域对象
  • @TestConfiguration、@ActiveProfiles、@Primary固定时钟Bean,用于实现可确定的测试设置
  • 现代Mocking API:@MockitoBean / @MockitoSpyBean;在Boot 4.0.x版本中@MockBean/@SpyBean已被弃用/移除
适用范围:根据参考规则和代码示例(优/劣)应用建议。如果是集成测试,请使用@322-frameworks-spring-boot-testing-integration-tests。

Constraints

约束条件

Before applying any test changes, ensure the project compiles. If compilation fails, stop immediately. After applying improvements, run full verification.
  • MANDATORY: Run
    ./mvnw compile
    or
    mvn compile
    before applying any change
  • SAFETY: If compilation fails, stop immediately
  • VERIFY: Run
    ./mvnw clean verify
    or
    mvn clean verify
    after applying improvements
  • BEFORE APPLYING: Read the reference for detailed rules and good/bad patterns
在应用任何测试变更之前,确保项目可以编译。如果编译失败,请立即停止。应用改进后,运行完整验证。
  • 强制要求:在应用任何变更前运行
    ./mvnw compile
    mvn compile
  • 安全提示:如果编译失败,立即停止
  • 验证:应用改进后运行
    ./mvnw clean verify
    mvn clean verify
  • 应用前须知:阅读参考文档以了解详细规则和优/劣模式示例

When to use this skill

何时使用本技能

  • Review Java code for Spring Boot unit tests
  • Apply best practices for Spring Boot unit tests in Java code
  • 审核Spring Boot单元测试的Java代码
  • 在Java代码中应用Spring Boot单元测试的最佳实践

Reference

参考资料

For detailed guidance, examples, and constraints, see references/321-frameworks-spring-boot-testing-unit-tests.md.
如需详细指导、示例和约束条件,请查看references/321-frameworks-spring-boot-testing-unit-tests.md