I am trying to write the unit test case for ListenableFuture adding Callback but I am not sure how to do it. Didn`t get anything useful on internet.
@Test
public void can_publish_data_to_kafka() {
String topic = someString(10);
String key = someAlphanumericString(5);
String data = someString(50);
SendResult sendResult = mock(SendResult.class);
ListenableFuture<SendResult<String, Object>> future = mock(ListenableFuture.class);
given(kafkaTemplate.send(topic, key, data)).willReturn(future);
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
return invocationOnMock.getArguments()[1];
}
});
service.method(key, topic, data);
}
Code for which i want to write test case
ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(topicName, key, data);
future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
@Override
public void onSuccess(SendResult<String, Object> stringKafkaBeanSendResult) {
RecordMetadata recordMetadata = stringKafkaBeanSendResult.getRecordMetadata();
LOGGER.info(String.format("sent message %s to topic %s partition %s with offset %s" + data.toString(), recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset()));
}
@Override
public void onFailure(Throwable throwable) {
LOGGER.error(String.format("unable to send message = %s to topic %s because of error %s" + data.toString(), topicName, throwable.getMessage()));
}
});
I am expecting a direction in which i should go towards for writing UT using mockito.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…