@ParameterizedTest是JUnit 5实现参数化测试的核心注解,需引入junit-jupiter-params依赖,支持@ValueSource、@CsvSource和@MethodSource等多种数据源,并可自定义测试名称提升可读性。

在 JUnit 5 中,@ParameterizedTest 是实现参数化测试的核心注解,它让同一个测试逻辑可以自动用多组输入数据反复执行,避免写大量重复的 @Test 方法。
1. 添加必要依赖
确保项目中已引入 JUnit 5 的参数化测试支持模块(junit-jupiter-params):
- Maven 依赖(需与
junit-jupiter版本一致,推荐 5.10+):
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.10.2</version>
<scope>test</scope>
</dependency>
2. 基本写法:用 @ValueSource 提供简单参数
适用于字符串、整数、布尔值等基础类型:
- 方法必须有参数,且参数类型与数据源匹配;
- 用
@ParameterizedTest替代@Test; - 用
@ValueSource注解提供一组值。
示例:
立即学习“Java免费学习笔记(深入)”;
@ParameterizedTest@ValueSource(strings = {"hello", "world", "junit"})
void shouldReturnStringLength(String input) {
assertEquals(input.length(), input.length()); // 简单示意
}
3. 多参数测试:用 @CsvSource 或 @MethodSource
当需要多个输入 + 一个期望输出时,推荐使用 @CsvSource(简洁)或 @MethodSource(灵活):
-
@CsvSource:每行是一组逗号分隔的参数,支持引号和 null 字面量; -
@MethodSource:自定义静态方法返回Stream<Arguments>,适合复杂对象或动态数据。
示例(CsvSource):
@ParameterizedTest@CsvSource({
"1, 2, 3",
"0, 5, 5",
"-3, 7, 4"
})
void shouldAddTwoNumbers(int a, int b, int expected) {
assertEquals(expected, a + b);
}
示例(MethodSource):
static Stream<Arguments> provideStringsForLength() {return Stream.of(
Arguments.of("a", 1),
Arguments.of("", 0),
Arguments.of("abc", 3)
);
}
@ParameterizedTest
@MethodSource("provideStringsForLength")
void shouldCalculateStringLength(String str, int expected) {
assertEquals(expected, str.length());
}
4. 自定义显示名称(可选但推荐)
用 name 属性让测试报告更清晰,支持占位符:
-
{index}:测试执行序号(从 1 开始); -
{arguments}:全部参数; -
{0},{1}:第 1、2 个参数(从 0 开始索引)。
示例:
立即学习“Java免费学习笔记(深入)”;
@ParameterizedTest(name = "测试第 {index} 组:{0} + {1} = {2}")@CsvSource({"1,2,3", "5,7,12"})
void shouldAdd(int a, int b, int expected) {
assertEquals(expected, a + b);
}
不复杂但容易忽略:确保测试类本身用 @ExtendWith(SpringExtension.class)(如需 Spring 支持),且 IDE 和构建工具(Maven/Gradle)已正确配置 JUnit 5 运行器。


















