Noa*_*ino 2 java junit parameterized-unit-test junit5
我试图传入一个数组来测试某个算法,但这些数组似乎没有正确传递或根本没有传递。我手动测试了算法,所以我知道它可以正常工作。如何传递数组以在 JUnit 5 中进行测试?
@ParameterizedTest
@CsvSource(value = {"[13,14,65,456,31,83],[1331,65456]"})
public void palindromeCombos(int[] input, int[] expected){
Palindrome pal = new Palindrome();
List<Integer> actual = pal.allPalindromes(input);
int[] result = new int[actual.size()];
for(int i = 0; i < actual.size(); i++){
result[i] = actual.get(i);
}
Assertions.assertArrayEquals(expected, result);
}
Run Code Online (Sandbox Code Playgroud)
当然,Pablo 的回答是正确的,但我个人并不喜欢解析字符串,如果我不是绝对必须的话。另一种方法可能是使用 aMethodSource
代替,并明确提供您需要的参数:
public static Stream<Arguments> palindromeCombos() {
return Stream.of(
Arguments.of(new int[]{13, 14, 65, 456, 31, 83}, new int[]{1331, 65456}));
}
@ParameterizedTest
@MethodSource
public void palindromeCombos(int[] input, int[] expected) {
// Test logic...
}
Run Code Online (Sandbox Code Playgroud)
由于数组没有隐式转换,因此可以使用显式转换,首先需要声明转换器类:
class IntArrayConverter implements ArgumentConverter {
@Override
public Object convert(Object source, ParameterContext context)
throws ArgumentConversionException {
if (!(source instanceof String)) {
throw new IllegalArgumentException(
"The argument should be a string: " + source);
}
try {
return Arrays.stream(((String) source).split(",")).mapToInt(Integer::parseInt).toArray();
} catch (Exception e) {
e.printStackTrace();
throw new IllegalArgumentException("Failed to convert", e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后您可以在测试中使用它:
@ParameterizedTest
@CsvSource(value = {
"13,14,65,456,31,83;1331,65456",
"1,2,3,4,5,6;10,20"}, delimiterString = ";")
public void palindromeCombos(@ConvertWith(IntArrayConverter.class) int[] input,
@ConvertWith(IntArrayConverter.class) int[] expected) {
System.out.println(Arrays.toString(input));
System.out.println(Arrays.toString(expected));
}
Run Code Online (Sandbox Code Playgroud)
请注意,我[]
从 CsvSource 中删除了 并将分隔符更改为;
,因此数组由以逗号分隔的整数列表表示。如果您愿意,可以保留您拥有的格式并在转换器类中处理它。对于这两个示例,输出为:
[13, 14, 65, 456, 31, 83]
[1331, 65456]
[1, 2, 3, 4, 5, 6]
[10, 20]
Run Code Online (Sandbox Code Playgroud)
如果您需要更多信息,可以查看这篇文章: https: //www.baeldung.com/parameterized-tests-junit-5
归档时间: |
|
查看次数: |
486 次 |
最近记录: |