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
You can write a test case like this.
@Test
public void can_publishDataToKafka() {
String key = someAlphanumericString();
String topic = someAlphaString(10);
long offset = somePositiveLong();
int partition = somePositiveInteger();
SiebelRecord siebelRecord = mock(SiebelRecord.class);
SendResult<String, Object> sendResult = mock(SendResult.class);
ListenableFuture<SendResult<String, Object>> responseFuture = mock(ListenableFuture.class);
RecordMetadata recordMetadata = new RecordMetadata(new TopicPartition(topic, partition), offset, 0L, 0L, 0L, 0, 0);
given(sendResult.getRecordMetadata()).willReturn(recordMetadata);
when(kafkaTemplate.send(topic, key, siebelRecord)).thenReturn(responseFuture);
doAnswer(invocationOnMock -> {
ListenableFutureCallback listenableFutureCallback = invocationOnMock.getArgument(0);
listenableFutureCallback.onSuccess(sendResult);
assertEquals(sendResult.getRecordMetadata().offset(), offset);
assertEquals(sendResult.getRecordMetadata().partition(), partition);
return null;
}).when(responseFuture).addCallback(any(ListenableFutureCallback.class));
service.publishDataToKafka(key, topic, siebelRecord);
verify(kafkaTemplate, times(1)).send(topic, key, siebelRecord);
}
@Test(expected = KafkaException.class)
public void can_capture_failure_publishDataToKafka() {
String key = someAlphanumericString();
String topic = someAlphaString(10);
String message = someString(20);
SiebelRecord siebelRecord = mock(SiebelRecord.class);
ListenableFuture<SendResult<String, Object>> responseFuture = mock(ListenableFuture.class);
Throwable throwable = mock(Throwable.class);
given(throwable.getMessage()).willReturn(message);
when(kafkaTemplate.send(topic, key, siebelRecord)).thenReturn(responseFuture);
doAnswer(invocationOnMock -> {
ListenableFutureCallback listenableFutureCallback = invocationOnMock.getArgument(0);
listenableFutureCallback.onFailure(throwable);
return null;
}).when(responseFuture).addCallback(any(ListenableFutureCallback.class));
service.publishDataToKafka(key, topic, siebelRecord);
}