131-java-testing-unit-testing
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseJava Unit testing guidelines
Java单元测试指南
Review and improve Java unit tests using modern JUnit 5, AssertJ, and Mockito best practices.
What is covered in this Skill?
- JUnit 5 annotations: ,
@Test,@BeforeEach,@AfterEach,@DisplayName,@Nested@ParameterizedTest - AssertJ fluent assertions: ,
assertThatassertThatThrownBy - Given-When-Then test structure, descriptive test naming, single-responsibility tests
- Test independence and isolated state
- Parameterized tests: /
@ValueSource/@CsvSource@MethodSource - Mockito dependency mocking: ,
@Mock,@InjectMocksMockitoExtension - Code coverage guidance (JaCoCo), package-private test visibility
- Testing anti-patterns: reflection, shared state, hard-coded values, testing implementation details
- Error handling: , exception messages
assertThatThrownBy - JSpecify null-safety: ,
@NullMarked@Nullable - RIGHT-BICEP coverage principles, A-TRIP test quality, CORRECT boundary condition verification
Scope: The reference is organized by examples (good/bad code patterns) for each core area. Apply recommendations based on applicable examples.
使用现代JUnit 5、AssertJ和Mockito最佳实践来评审和改进Java单元测试。
本Skill涵盖哪些内容?
- JUnit 5注解:、
@Test、@BeforeEach、@AfterEach、@DisplayName、@Nested@ParameterizedTest - AssertJ流畅断言:、
assertThatassertThatThrownBy - Given-When-Then测试结构、描述性测试命名、单一职责测试
- 测试独立性与隔离状态
- 参数化测试:/
@ValueSource/@CsvSource@MethodSource - Mockito依赖模拟:、
@Mock、@InjectMocksMockitoExtension - 代码覆盖率指导(JaCoCo)、包私有测试可见性
- 测试反模式:反射、共享状态、硬编码值、测试实现细节
- 错误处理:、异常消息
assertThatThrownBy - JSpecify空安全:、
@NullMarked@Nullable - RIGHT-BICEP覆盖原则、A-TRIP测试质量、CORRECT边界条件验证
范围:参考文档按每个核心领域的示例(好/坏代码模式)组织。请根据适用示例应用建议。
Constraints
约束条件
Before applying any unit test changes, ensure the project compiles. If compilation fails, stop immediately — do not proceed until resolved. After applying improvements, run full verification.
- MANDATORY: Run or
./mvnw compilebefore applying any changemvn compile - SAFETY: If compilation fails, stop immediately and do not proceed — compilation failure is a blocking condition
- VERIFY: Run or
./mvnw clean verifyafter applying improvementsmvn clean verify - BEFORE APPLYING: Read the reference for detailed examples, good/bad patterns, and constraints
在应用任何单元测试更改之前,确保项目可编译。如果编译失败,请立即停止——在问题解决前不要继续。应用改进后,运行完整验证。
- 强制要求:在应用任何更改前运行或
./mvnw compilemvn compile - 安全要求:如果编译失败,立即停止且不要继续——编译失败是阻塞条件
- 验证要求:应用改进后运行或
./mvnw clean verifymvn clean verify - 应用前须知:阅读参考文档以获取详细示例、好/坏模式及约束条件
Reference
参考资料
For detailed guidance, examples, and constraints, see references/131-java-testing-unit-testing.md.
如需详细指导、示例和约束条件,请参阅references/131-java-testing-unit-testing.md