使用 Mockito 对具有相同参数的同一方法进行多次调用

2022-08-31 04:33:49

有没有办法让存根方法在后续调用时返回不同的对象?我想这样做来测试来自.即,测试无论方法的返回顺序如何,结果都保持不变。ExecutorCompletionService

我想要测试的代码看起来像这样。

// Create an completion service so we can group these tasks together
ExecutorCompletionService<T> completionService =
        new ExecutorCompletionService<T>(service);

// Add all these tasks to the completion service
for (Callable<T> t : ts)
    completionService.submit(request);

// As an when each call finished, add it to the response set.
for (int i = 0; i < calls.size(); i ++) {
    try {
        T t = completionService.take().get();
        // do some stuff that I want to test
    } catch (...) { }        
}

答案 1

怎么样

when( method-call ).thenReturn( value1, value2, value3 );

您可以在 thenReturn 的括号中放置任意数量的参数,前提是它们都是正确的类型。第一次调用方法时将返回第一个值,然后返回第二个答案,依此类推。一旦所有其他值用完,将重复返回最后一个值。


答案 2

您可以使用 thenAnswer 方法执行此操作(当与 when 链接时):

when(someMock.someMethod()).thenAnswer(new Answer() {
    private int count = 0;

    public Object answer(InvocationOnMock invocation) {
        if (count++ == 1)
            return 1;

        return 2;
    }
});

或者使用等效的静态 doAnswer 方法:

doAnswer(new Answer() {
    private int count = 0;

    public Object answer(InvocationOnMock invocation) {
        if (count++ == 1)
            return 1;

        return 2;
    }
}).when(someMock).someMethod();

推荐