我写了一个模型示例来说明这一点,而不会泄露任何机密信息.这是一个“虚拟”示例,它什么都不做,但问题发生在测试初始化器中.
- @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);
- }
- }
基本上我有一个测试构造函数,它接受本地列表变量的多个参数,我想通过数组初始化器填充它.测试方法将正确处理本地列表变量 – 我已删除此逻辑以简化测试.
当我写这篇文章时,我的IDE没有关于语法和测试类构建的抱怨而没有任何编译错误.但是,当我运行它时,我得到:
- 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)
这里到底出了什么问题,我如何正确使用这种模式?
解决方法
现在无法测试它,但我想,如果你调用一个带有变量参数的方法或构造函数,你必须使用数组而不是变量值列表来调用它.
如果我是对的,那么这应该有效:
- @Parameters
- public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][] {
- {0,new String[]{"hello","goodbye"}},new String[]{"farewell"}}
- });
- }
一些解释
在源代码级别,我们可以写
- test = ExampleParamTest(0,"one","two");
编译器会将其转换为字符串数组. JUnit使用反射和调用API,从这个角度来看,构造函数签名是
- public ExampleParamTest(int i,String[] strings);