Java枚举在mockito&then;返回的列表中

时间:2015-10-23 20:33:57

标签: java list junit mockito enumeration

有没有办法在mockito的thenReturn函数中枚举列表中的项目,所以我返回列表中的每个项目。到目前为止,我已经做到了这一点:

List<Foo> returns = new ArrayList<Foo>();
//populate returns list

Mockito.when( /* some function is called */ ).thenReturn(returns.get(0), returns.get(1), returns.get(2), returns.get(3));

这正是我想要的方式。每次调用该函数时,它都会从列表中返回一个不同的对象,例如get(1)get(2)等。

但我希望简化这一点,并使其对任何大小的列表更具动态性,以防我有一个大小为100的列表。我尝试过这样的事情:

Mockito.when( /* some function is called */ ).thenReturn(
    for(Foo foo : returns) {
        return foo;
    }
);

我也试过这个:

Mockito.when(service.findFinancialInstrumentById(eq(1L))).thenReturn(
    for (int i=0; i<returns.size(); i++) {
        returns.get(i);
    }
);

但这不起作用....所以我如何在thenReturn中列举这个列表....我遇到了其他类似then的方法或者answer但我不确定在这种情况下哪一个效果最佳。

2 个答案:

答案 0 :(得分:16)

thenReturn()方法签名是

thenReturn(T value, T... values)

所以它需要一个T的实例,然后是一个vararg T ...,它是一个数组的语法糖。所以你可以使用

when(foo.bar()).thenReturn(list.get(0), 
                           list.subList(1, list.size()).toArray(new Foo[]{}));

但更简洁的解决方案是创建一个Answer实现,它将List作为参数,并在每次使用时回答列表的下一个元素。然后使用

when(foo.bar()).thenAnswer(new SequenceAnswer<>(list));

例如:

private static class SequenceAnswer<T> implements Answer<T> {

    private Iterator<T> resultIterator;

    // the last element is always returned once the iterator is exhausted, as with thenReturn()
    private T last;

    public SequenceAnswer(List<T> results) {
        this.resultIterator = results.iterator();
        this.last = results.get(results.size() - 1);
    }

    @Override
    public T answer(InvocationOnMock invocation) throws Throwable {
        if (resultIterator.hasNext()) {
            return resultIterator.next();
        }
        return last;
    }
}

答案 1 :(得分:12)

另一种做法(但个人而言,我更喜欢JB Nizet SequenceAnswer的想法),会是这样的......

OngoingStubbing stubbing = Mockito.when(...);
for(Object obj : list) {
    stubbing = stubbing.thenReturn(obj);
}
相关问题