我写了一个模型示例来说明这一点,但没有暴露任何 secret 信息。这是一个什么都不做的“虚拟”示例,但问题出现在测试初始化程序中。
@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"}},
{1, new String[]{"farewell"}}
});
}
一些解释
在源代码层面,我们可以这样写
test = ExampleParamTest(0, "one", "two");
编译器会将其转换为字符串数组。 JUnit使用反射和调用API,从这个角度看,构造函数签名是
public ExampleParamTest(int i, String[] strings);
所以要调用构造函数——这就是 JUnit 内部所做的——你必须传递一个整数和一个字符串数组。
关于java - 如何将 JUnit Parameterized runner 与 varargs 构造函数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3493588/