[英]JUnit Test - ParameterizedTests - 'No implicit conversion of type java.lang.Integer to type [Ljava.lang.Integer;'
Using JUnit5.使用 JUnit5。 This doesn't seem to be behaving correctly to me, I'm likely missing something.
这对我来说似乎表现不正确,我可能会遗漏一些东西。
@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})
);
}
Produces the error:产生错误:
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;
I've also tried the above code using int
instead of Integer
, but this works correctly.我也尝试过使用
int
而不是Integer
的上述代码,但这可以正常工作。
This works with no error:这没有错误:
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);
}
}
You're getting this error, because the method declaration of Arguments.of()
is the following:您收到此错误,因为
Arguments.of()
的方法声明如下:
public static Arguments of(Object... arguments)
Object...
indicates a varargs (variable arguments) parameter, so when writing: Object...
表示一个varargs(可变参数)参数,所以写的时候:
Arguments.of(1, 2, 3)
at compile time, java will desuger this into an array:在编译时, java 会将其放入数组中:
Arguments.of(new Object[]{1, 2, 3})
The problem that you're having can be shown by the following:您遇到的问题可以通过以下方式显示:
Integer[] ints = new Integer[]{1, 2, 3};
Object[] objs = ints; // works
So when you write:所以当你写:
Arguments.of(new Integer[]{12, 42, 52, 1234, 12, 425, 4})
Then java will just pass this array directly into the method, it would effectively behave the same as both of the following:然后 java 将直接将此数组传递给方法,它的行为实际上与以下两者相同:
Arguments.of(new Object[]{12, 42, 52, 1234, 12, 425, 4})
Arguments.of(12, 42, 52, 1234, 12, 425, 4)
To overcome this problem, you need to cast your Integer[]
array directly to Object
, that way it will be wrapped inside another array:为了克服这个问题,您需要将
Integer[]
数组直接转换为Object
,这样它将被包装在另一个数组中:
Arguments.of((Object) new Integer[]{12, 42, 52, 1234, 12, 425, 4})
Will become:会变成:
Arguments.of(new Object[]{new Integer[]{12, 42, 52, 1234, 12, 425, 4}})
As you've noted it works correctly with int[]
because the following doesn't work:正如您所注意到的,它可以与
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.