如何在mockito中使用回调存根连续调用

时间:2016-11-22 10:41:21

标签: java android unit-testing mockito

使用Mockito时,您可以存储方法调用,如:

when(mock.someMethod("some arg"))
    .thenThrow(new RuntimeException())
    .thenReturn("foo");

但是当你的方法返回void时,你需要使用这种格式存根:

    doAnswer(new Answer() {..).when(mock). someMethod("some arg");

想象一下,我有Worker.class这样的

class Worker {

   void doWork(Callback callback) {
        boolean success= ...;
        if(success){
            callback.onSuccess();
        }else {
            callback.onFail();
        }
   }

}

您可以使用以下代码存根调用:

    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Callback callback= invocation.getArguments()[0];
            callback.onSuccess();
            return null;
        }
    }).when(mockWorker).doWork(any(Callback.class));

现在假设我想要连续三次调用工作人员来调用onFail, onSuccess, onFail我该怎么做?我是否需要在每个answer(InvocationOnMock invocation)电话中重新配置模拟?

1 个答案:

答案 0 :(得分:2)

奥基找到了答案。您只需要将调用链接到doAnswer,如:

doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        Callback callback= invocation.getArguments()[0];
        callback.onFail();
        return null;
    }
}).
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        Callback callback= invocation.getArguments()[0];
        callback.onSuccess();
        return null;
    }
}).
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        Callback callback= invocation.getArguments()[0];
        callback.onFail();
        return null;
    }
}).when(mockWorker).doWork(any(Callback.class));