How to use JUnit Parameterized runner with varargs constructor?

I wrote a sample layout to illustrate this without revealing anything confidential. This is an example of "dummy" that does nothing, but the problem arises in the test initializer.

@RunWith(Parameterized.class) public class ExampleParamTest { int ordinal; List<String> strings; public ExampleParamTest(int ordinal, String... strings) { this.ordinal = ordinal; if (strings.length == 0) { this.strings = null; } else { this.strings = Arrays.asList(strings); } } @Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { {0, "hello", "goodbye"}, {1, "farewell"} }); } @Test public void doTest() { Assert.assertTrue(true); } } 

Basically, I have a test constructor that takes several arguments for a local list variable, and I want to populate this through an array initializer. The verification method correctly processes the local list variable - I removed this logic to simplify the test.

When I write this, my IDE has no complaints about the syntax and builds of the test class without any compilation errors. However, when I run it, I get:

 doTest[0]: java.lang.IllegalArgumentException: wrong number of arguments at java.lang.reflect.Constructor.newInstance(Unknown Source) doTest[1]: java.lang.IllegalArgumentException: argument type mismatch at java.lang.reflect.Constructor.newInstance(Unknown Source) 

What exactly happened here and how to use this template correctly?

+6
java junit
source share
1 answer

I can’t check it right now, but I think if you call a method or constructor with variable arguments, you should call it with an array instead of a list of variables.

If I'm right, then this should work:

 @Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { {0, new String[]{"hello", "goodbye"}}, {1, new String[]{"farewell"}} }); } 

Some explanation

At the source code level, we can write

 test = ExampleParamTest(0, "one", "two"); 

The compiler will convert this to an array of strings. JUnit uses the reflection and call API, and from this point of view, the signature of the constructors

 public ExampleParamTest(int i, String[] strings); 

So, to call the constructor - and what JUnit does internally - you need to pass an integer and an array of String.

+11
source share

All Articles