java参数化测试中的junit传递int数组

1wnzp6jl  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(429)

我试图传入一个数组来测试某个算法,但是数组似乎没有正确地传递,或者根本没有传递。我手动测试了这个算法,所以我知道它能正常工作。如何在junit5中传递数组进行测试?

@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);    
}
mznpcxlj

mznpcxlj1#

当然,pablo的回答是正确的,但就我个人而言,如果我不一定要解析字符串的话,我并不喜欢。另一种方法是使用 MethodSource 而是显式提供所需的参数:

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...
}
8iwquhpp

8iwquhpp2#

由于数组没有隐式转换,因此可以使用显式转换,首先需要声明转换器类:

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);
            }
        }
    }

然后你可以在测试中使用它:

@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));
    }

注意,我删除了 [] 并将分隔符更改为 ; ,因此数组由逗号分隔的整数列表表示。如果需要,可以保留现有的格式,并在converter类中处理它。对于这两个示例,输出为:

[13, 14, 65, 456, 31, 83]
[1331, 65456]

[1, 2, 3, 4, 5, 6]
[10, 20]

如果您需要更多信息,请查看以下帖子:https://www.baeldung.com/parameterized-tests-junit-5

相关问题