Issue
I am trying to write a JUnit test for a function that finds the median for a given array of double
elements.
However, I am struggling with passing the parameters. My code looks like this:
@RunWith(Parameterized.class)
public class MedianParameterizedTest extends TestCase {
private Double[] numbers;
private Double expectedMedian;
public MedianParameterizedTest(Double[] numbers, double expectedMedian){
this.numbers = numbers;
this.expectedMedian = expectedMedian;
}
@Parameterized.Parameters
public static Collection medianArrays() {
return Arrays.asList(new Object[][] {
{ {-5.0,-4.0,3.0}, -4.0}
});
}
@Test
public void test1() {
//doing test
}
}
But this gives me an illegal initializer for java.lang.Object error for the medianArrays collection and I can't find out why.
Solution
You need to create the first (array) argument for each test using new Double[]
.
You have three levels of nested arrays in your code:
- the top level is the entire collection, with one element per test case,
- the next level down contains the two parameters for each test case,
- the innermost level, within the first argument for each test case, contains all of the numbers that you wish to calculate the median on in one test case.
After new Object[][]
, Java knows that two levels of nested arrays are to be expected. After new Object[][] {
, it still knows that there is one more level of array to expect, but after new Object[][] { {
, it's not expecting any more further levels of nested array. If you want to create an array at this point you must specify the type.
Try the following instead:
@Parameterized.Parameters
public static Collection medianArrays() {
return Arrays.asList(new Object[][] {
{ new Double[] {-5.0,-4.0,3.0}, -4.0}
});
}
Answered By - Luke Woodward
Answer Checked By - Robin (JavaFixing Admin)