gpt4 book ai didi

java - JUnit 测试 - 参数化测试 - 'No implicit conversion of type java.lang.Integer to type [Ljava.lang.Integer;'

转载 作者:行者123 更新时间:2023-12-05 02:43:58 25 4
gpt4 key购买 nike

使用 JUnit5。这对我来说似乎不正确,我可能遗漏了一些东西。

    @ParameterizedTest
@MethodSource
void testFunc(Integer arr []) {
for(Integer i : arr){
System.out.print(i + " ");
}
System.out.println("\n");
}

static Stream<Arguments> testFunc() {
return Stream.of(
Arguments.of(new Integer [] {12, 42, 52, 1234, 12, 425, 4}),
Arguments.of(new Integer [] {12, 42, 52, 1234, 12, 425}),
Arguments.of(new Integer [] {12})
);
}

产生错误:

org.junit.jupiter.api.extension.ParameterResolutionException: Error converting parameter at index 0: No implicit conversion to convert object of type java.lang.Integer to type [Ljava.lang.Integer;

我也尝试过使用 int 而不是 Integer 上面的代码,但它工作正常。

这没有错误:

    public static void main(String args[]){
test(new Integer []{12, 42, 52, 1234, 12, 425, 4});
}

static void test(Integer[] arr) {
for(Integer a : arr){
System.out.println(a);
}
}

最佳答案

您收到此错误,因为 Arguments.of() 的方法声明是以下内容:

public static Arguments of(Object... arguments)

Object...表示一个varargs(可变参数)参数,所以写的时候:

Arguments.of(1, 2, 3)

在编译时,java 会将其解压到一个数组中:

Arguments.of(new Object[]{1, 2, 3})

您遇到的问题可以通过以下方式显示:

Integer[] ints = new Integer[]{1, 2, 3};
Object[] objs = ints; // works

所以当你写的时候:

Arguments.of(new Integer[]{12, 42, 52, 1234, 12, 425, 4})

然后 java 将把这个数组直接传递给方法,它的行为实际上与以下两个相同:

Arguments.of(new Object[]{12, 42, 52, 1234, 12, 425, 4})
Arguments.of(12, 42, 52, 1234, 12, 425, 4)

为了解决这个问题,您需要将Integer[] 数组直接转换为Object,这样它就会被包裹在另一个数组中:

Arguments.of((Object) new Integer[]{12, 42, 52, 1234, 12, 425, 4})

将成为:

Arguments.of(new Object[]{new Integer[]{12, 42, 52, 1234, 12, 425, 4}})

正如您所注意到的,它可以与 int[] 一起正常工作,因为以下内容不起作用:

int[] ints = new int[]{1, 2, 3};
Object[] objs = ints; // int[] cannot be assigned to Object[]

关于java - JUnit 测试 - 参数化测试 - 'No implicit conversion of type java.lang.Integer to type [Ljava.lang.Integer;',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66675658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com