使用 Mockito 多次调用具有相同参数的相同方法 [英] Using Mockito with multiple calls to the same method with the same arguments

查看:33
本文介绍了使用 Mockito 多次调用具有相同参数的相同方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to have a stubbed method return different objects on subsequent invocations? I'd like to do this to test nondeterminate responses from an ExecutorCompletionService. i.e. to test that irrespective of the return order of the methods, the outcome remains constant.

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

The code I'm looking to test looks something like this.

// 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 (...) { }        
}

推荐答案

您可以使用 thenAnswer 方法(当与 when):

You can do that using the thenAnswer method (when chaining with when):

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

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

        return 2;
    }
});

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

Or using the equivalent, static doAnswer method:

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

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

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

这篇关于使用 Mockito 多次调用具有相同参数的相同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆