使用 Mockito 调用回调 [英] Calling callbacks with Mockito

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

问题描述

我有一些代码

service.doAction(request, Callback<Response> callback);

如何使用 Mockito 抓取回调对象,并调用 callback.reply(x)

How can I using Mockito grab the callback object, and call callback.reply(x)

推荐答案

您想设置一个 Answer 对象来执行此操作.看看 Mockito 文档,在https://static.javadoc.io/org.mockito/mockito-core/2.8.47/org/mockito/Mockito.html#answer_stubs

You want to set up an Answer object that does that. Have a look at the Mockito documentation, at https://static.javadoc.io/org.mockito/mockito-core/2.8.47/org/mockito/Mockito.html#answer_stubs

你可能会写一些类似的东西

You might write something like

when(mockService.doAction(any(Request.class), any(Callback.class))).thenAnswer(
    new Answer<Object>() {
        Object answer(InvocationOnMock invocation) {
            ((Callback<Response>) invocation.getArguments()[1]).reply(x);
            return null;
        }
});

(当然,将 x 替换为它应该的样子)

(replacing x with whatever it ought to be, of course)

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

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