如何模拟 KafkaTemplate 的结果 [英] How to mock result from KafkaTemplate

查看:37
本文介绍了如何模拟 KafkaTemplate 的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种发送 kafka 消息的方法,如下所示:

I have a method for sending kafka message like this:

@Async
public void sendMessage(String topicName, Message message) {
    ListenableFuture<SendResult<String, Message >> future = kafkaTemplate.send(topicName, message);

    future.addCallback(new ListenableFutureCallback<>() {

        @Override
        public void onSuccess(SendResult<String, Message > result) {
            //do nothing
        }

        @Override
        public void onFailure(Throwable ex) {
            log.error("something wrong happened"!);
        }
    });
}

现在我正在为它编写单元测试.我还想测试两个回调方法 onSuccessonFailure 方法,所以我的想法是模拟 KafkaTemplate,例如:

And now I am writing unit tests for it. I would like to test also the two callback methods onSuccess and onFailure methods, so my I idea is to mock the KafkaTemplate, something like :

KafkaTemplate kafkaTemplate = Mockito.mock(KafkaTemplate.class);

但现在我被这两种情况的模拟结果困住了:

But now I am getting stuck on the mocking result for these two cases:

when(kafkaTemplate.send(anyString(), any(Message.class))).thenReturn(????);

对于案例成功和案例失败,我应该在 thenReturn 方法中放什么?请问有人有什么想法吗?非常感谢!

what should I put in the thenReturn method for the case success and for the case failure? Does anyone have an idea please? Thank you very much!

推荐答案

你可以模拟模板,但最好模拟界面.

You can mock the template but it's better to mock the interface.

    Sender sender = new Sender();
    KafkaOperations template = mock(KafkaOperations.class);
    SettableListenableFuture<SendResult<String, String>> future = new SettableListenableFuture<>();
    when(template.send(anyString(), any(Message.class))).thenReturn(future);
    sender.setTemplate(template);
    sender.send(...);

    future.set(new SendResult<>(...));

    ...or...

    future.setException(...

这篇关于如何模拟 KafkaTemplate 的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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