Question
What is the correct way to pass an integer array as a parameter in a JUnit parameterized test?
@RunWith(Parameterized.class)
public class MyParameterizedTest {
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ new int[] { 1, 2, 3 } },
{ new int[] { 4, 5, 6 } },
{ new int[] { 7, 8, 9 } }
});
}
private int[] input;
public MyParameterizedTest(int[] input) {
this.input = input;
}
@Test
public void testArraySum() {
assertEquals(6, Arrays.stream(input).sum());
}
}
Answer
Passing an integer array to a parameterized test in Java can enhance your testing strategy by allowing multiple scenarios to be run using the same test logic. Java's JUnit framework provides a straightforward way to accomplish this with the use of parameterized tests.
@RunWith(Parameterized.class)
public class MyParameterizedTest {
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ new int[] { 1, 2, 3 } },
{ new int[] { 4, 5, 6 } },
{ new int[] { 7, 8, 9 } }
});
}
private int[] input;
public MyParameterizedTest(int[] input) {
this.input = input;
}
@Test
public void testArraySum() {
assertEquals(6, Arrays.stream(input).sum());
}
}
Causes
- Understanding of JUnit framework
- Usage of Parameter annotation
- Handling arrays within test parameters
Solutions
- Define a test class using @RunWith(Parameterized.class) annotation.
- Create a method annotated with @Parameterized.Parameters to provide the array inputs.
- Ensure your test method accepts the array as a parameter.
Common Mistakes
Mistake: Not properly setting up the parameterized test structure.
Solution: Ensure the test class is annotated with @RunWith(Parameterized.class) and correctly implements the parameters method.
Mistake: Forgetting to convert the integer array into a suitable format for tests.
Solution: Use Java collections like Collections.singletonList() or Arrays.asList() to wrap your arrays.
Helpers
- Java parameterized test
- JUnit parameterized tests
- passing int array in JUnit
- Java testing best practices
- JUnit array parameters