如何将动态数量的列表传递给varargs方法?

时间:2014-10-09 02:58:05

标签: java list unit-testing mockito variadic-functions

我试图为单元测试编写一个可重用的方法,以便能够模拟返回List<String>的某个类的行为,以便我可以调用此mockInstansiate方法设置模拟。如何为thenReturn()方法传入多个列表?我知道我可以做.thenReturn().thenReturn().thenReturn etc,但我希望能够让这种动态变得充满活力,因为我不知道我会有多少名单。

我得到的错误是:

Cannot create a generic array of ArrayList<String>

代码:

private void mockInstansiate (List<String> wheels) {
    Machine machine = mock(Machine.class);
    List<List<String>> results = new ArrayList<List<String>>();

    for(String wheel : wheels) {
        List<String> result = new ArrayList<String>();
        result.add(wheel);

        results.add(result);
    }

    List<String> wheel1 = results.remove(0);

    /* Issue here, I'm trying to create an array of List<String> to pass
     * into the second part of thenReturn() */
    List<String>[] otherLists = new ArrayList<String>[9];
    when(machine.getLists()).thenReturn(wheel1, results.toArray(otherLists));
}

class Machine {
    public List<String> getLists() {
        // Doesn't matter what's here, it's being mocked out
    }
}

0 个答案:

没有答案