How to mock result from KafkaTemplate

杀马特。学长 韩版系。学妹 提交于 2020-05-28 04:33:05

问题


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"!);
        }
    });
}

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(????);

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!


回答1:


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(...


来源:https://stackoverflow.com/questions/57475464/how-to-mock-result-from-kafkatemplate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!