[英]ClassCast Exception in java, cannot cast to Ljava.lang.Integer
[英]JUnit Test - ParameterizedTests - 'No implicit conversion of type java.lang.Integer to type [Ljava.lang.Integer;'
使用 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[]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.