参数源
参数源 | 说明 |
---|---|
@ValueSource | 见案例 |
@EnumSource | 见案例 |
@MethodSource | 见案例 |
@CsvSource | 见案例 |
@CsvFileSource | 见案例 |
@ArgumentsSource | 见案例 |
案例
参数化测试可以使用不同的参数多次运行测试。它们的声明就像常规@Test方法一样,但使用 @ParameterizedTest注释代替。此外,您必须至少声明一个源,该源将为每次调用提供参数,然后在测试方法中使用这些参数
1、@ParameterizedTest+@ValueSource参数化
@ValueSource是最简单的来源之一。它允许您指定单个文字值数组,并且只能用于为每个参数化测试调用提供一个参数
支持以下类型的文字值@ValueSource。
- short
- byte
- int
- long
- float
- double
- char
- boolean
- java.lang.String
- java.lang.Class
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testWithValueSource(int argument) {
assertTrue(argument > 0 && argument < 4);
}
测试结果:

2、@ParameterizedTest+@CsvSource参数化
@ParameterizedTest
@CsvSource({
"apple, 1",
"banana, 2",
"'lemon, lime', 0xF1"
})
void testWithCsvSource(String fruit, int rank) {
assertNotNull(fruit);
assertNotEquals(0, rank);
}
测试结果:

3、@ParameterizedTest+@CsvFileSource参数化
Junit5提供了@CsvFileSourc注解来实现csv数据格式的数据驱动,可以传递csv文件路径来读取数据,写法如下:
- csv数据文件:
Country, reference
Sweden, 1
Poland, 2
"United States of America", 3
- 示例代码
@ParameterizedTest
@CsvFileSource(resources = "/two-column.csv", numLinesToSkip = 1)
void testWithCsvFileSource(String country, int reference) {
assertNotNull(country);
assertNotEquals(0, reference);
}
测试结果:

注意:使用CsvFileSource时,上面的文件一定要增加给numLinesToSkip(默认为0)赋值为1,不然会把Country, reference也参数化进去
4、@ParameterizedTest+@EnumSource参数化
@ParameterizedTest
@EnumSource(ChronoUnit.class)
void testWithEnumSource(TemporalUnit unit) {
assertNotNull(unit);
}
测试结果:

5、@ParameterizedTest+@ArgumentsSource参数化
@ArgumentsSource可用于指定自定义的、可重用的ArgumentsProvider. 请注意,ArgumentsProvider必须将的实现声明为顶级类或static嵌套类
@ParameterizedTest
@ArgumentsSource(MyArgumentsProvider.class)
void testWithArgumentsSource(String argument) {
assertNotNull(argument);
}
public static class MyArgumentsProvider implements ArgumentsProvider {
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
return Stream.of("apple", "banana").map(Arguments::of);
}
}
测试结果:

6、@ParameterizedTest+@MethodSource参数化
- 显式提供工厂方法名称
@ParameterizedTest
@MethodSource("stringProvider")
void testWithExplicitLocalMethodSource(String argument) {
assertNotNull(argument);
}
static Stream<String> stringProvider() {
return Stream.of("apple", "banana");
}
测试结果:

- 与当前方法同名的工厂方法
@ParameterizedTest
@MethodSource
void testWithDefaultLocalMethodSource(String argument) {
assertNotNull(argument);
}
static Stream<String> testWithDefaultLocalMethodSource() {
return Stream.of("apple", "banana", "orange");
}
测试结果:

网友评论