java-junit
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseJUnit 5+ Best Practices
JUnit 5+ 最佳实践
Your goal is to help me write effective unit tests with JUnit 5, covering both standard and data-driven testing approaches.
本文旨在帮助你使用JUnit 5编写高效的单元测试,涵盖标准测试和数据驱动测试两种方法。
Project Setup
项目设置
- Use a standard Maven or Gradle project structure.
- Place test source code in .
src/test/java - Include dependencies for ,
junit-jupiter-api, andjunit-jupiter-enginefor parameterized tests.junit-jupiter-params - Use build tool commands to run tests: or
mvn test.gradle test
- 使用标准的Maven或Gradle项目结构。
- 将测试源代码放置在目录下。
src/test/java - 引入、
junit-jupiter-api以及用于参数化测试的junit-jupiter-engine依赖。junit-jupiter-params - 使用构建工具命令运行测试:或
mvn test。gradle test
Test Structure
测试结构
- Test classes should have a suffix, e.g.,
Testfor aCalculatorTestclass.Calculator - Use for test methods.
@Test - Follow the Arrange-Act-Assert (AAA) pattern.
- Name tests using a descriptive convention, like .
methodName_should_expectedBehavior_when_scenario - Use and
@BeforeEachfor per-test setup and teardown.@AfterEach - Use and
@BeforeAllfor per-class setup and teardown (must be static methods).@AfterAll - Use to provide a human-readable name for test classes and methods.
@DisplayName
- 测试类应带有后缀,例如针对
Test类的测试类命名为Calculator。CalculatorTest - 为测试方法添加注解。
@Test - 遵循准备-执行-断言(AAA)模式。
- 使用描述性命名规则为测试命名,例如。
methodName_should_expectedBehavior_when_scenario - 使用和
@BeforeEach实现测试方法级别的前置准备和后置清理。@AfterEach - 使用和
@BeforeAll实现测试类级别的前置准备和后置清理(必须为静态方法)。@AfterAll - 使用为测试类和方法提供易读的名称。
@DisplayName
Standard Tests
标准测试
- Keep tests focused on a single behavior.
- Avoid testing multiple conditions in one test method.
- Make tests independent and idempotent (can run in any order).
- Avoid test interdependencies.
- 保持测试聚焦于单一行为。
- 避免在一个测试方法中测试多个条件。
- 确保测试独立且幂等(可按任意顺序运行)。
- 避免测试之间存在依赖关系。
Data-Driven (Parameterized) Tests
数据驱动(参数化)测试
- Use to mark a method as a parameterized test.
@ParameterizedTest - Use for simple literal values (strings, ints, etc.).
@ValueSource - Use to refer to a factory method that provides test arguments as a
@MethodSource,Stream, etc.Collection - Use for inline comma-separated values.
@CsvSource - Use to use a CSV file from the classpath.
@CsvFileSource - Use to use enum constants.
@EnumSource
- 使用标记参数化测试方法。
@ParameterizedTest - 使用传入简单字面量值(字符串、整数等)。
@ValueSource - 使用引用提供测试参数的工厂方法,参数格式可为
@MethodSource、Stream等。Collection - 使用传入内联的逗号分隔值。
@CsvSource - 使用从类路径中读取CSV文件作为测试参数。
@CsvFileSource - 使用传入枚举常量作为测试参数。
@EnumSource
Assertions
断言
- Use the static methods from (e.g.,
org.junit.jupiter.api.Assertions,assertEquals,assertTrue).assertNotNull - For more fluent and readable assertions, consider using a library like AssertJ ().
assertThat(...).is... - Use or
assertThrowsto test for exceptions.assertDoesNotThrow - Group related assertions with to ensure all assertions are checked before the test fails.
assertAll - Use descriptive messages in assertions to provide clarity on failure.
- 使用中的静态方法(例如
org.junit.jupiter.api.Assertions、assertEquals、assertTrue)。assertNotNull - 若需要更流畅易读的断言方式,可考虑使用AssertJ库(语法如)。
assertThat(...).is... - 使用或
assertThrows测试异常场景。assertDoesNotThrow - 使用对相关断言进行分组,确保所有断言在测试失败前都会被检查。
assertAll - 在断言中添加描述性消息,以便在测试失败时提供清晰的原因说明。
Mocking and Isolation
模拟与隔离
- Use a mocking framework like Mockito to create mock objects for dependencies.
- Use and
@Mockannotations from Mockito to simplify mock creation and injection.@InjectMocks - Use interfaces to facilitate mocking.
- 使用Mockito等模拟框架为依赖项创建模拟对象。
- 使用Mockito的和
@Mock注解简化模拟对象的创建和注入。@InjectMocks - 使用接口以便于模拟操作。
Test Organization
测试组织
- Group tests by feature or component using packages.
- Use to categorize tests (e.g.,
@Tag,@Tag("fast")).@Tag("integration") - Use and
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)to control test execution order when strictly necessary.@Order - Use to temporarily skip a test method or class, providing a reason.
@Disabled - Use to group tests in a nested inner class for better organization and structure.
@Nested
- 按功能或组件使用包对测试进行分组。
- 使用对测试进行分类(例如
@Tag、@Tag("fast"))。@Tag("integration") - 当确实需要控制测试执行顺序时,使用和
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)注解。@Order - 使用临时跳过某个测试方法或类,并提供跳过原因。
@Disabled - 使用将测试分组到嵌套内部类中,以实现更好的组织和结构。
@Nested