Using 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.
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:
public static Arguments of(Object... arguments)
Object... indicates a varargs (variable arguments) parameter, so when writing:
Arguments.of(1, 2, 3)
at compile time, java will desuger this into an array:
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:
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:
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[] ints = new int[]{1, 2, 3};
Object[] objs = ints; // int[] cannot be assigned to Object[]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With