我想围绕调用Kafka进行一些测试。我的Kafka通话具有以下回调设置,请参见下文:
@Async // allows function to be async. the config also has to be set
@Override
public void publishEventToTopic() {
ListenableFuture<SendResult<String, KafkaRequest>> future = kafkaTemplate.send(topic, request);
future.addCallback(new ListenableFutureCallback<SendResult<String, KafkaRequest>>() {
@Override
public void onSuccess(SendResult<String, KafkaRequest> result) {
log.info("Success");
}
@Override
public void onFailure(Throwable ex) {
log.info("Failure");
}
});
}
我想做的是测试两种情况(onSuccess和onFailure)。我尝试遵循此SO question,但遇到一个错误,提示“主题不能为空”。这是我尝试过的:
@Test
public void test2() {
String key = "test1";
String topic = "sender.t";
long offset = 1;
int partition = 0;
SendResult<String, Object> sendResult = mock(SendResult.class);
ListenableFuture<SendResult<String, KafkaRequest>> responseFuture = mock(ListenableFuture.class);
RecordMetadata recordMetadata = new RecordMetadata(new TopicPartition(topic, partition), offset, 0L, 0L, 0L, 0, 0);
ProducerRecord producerRecord = new ProducerRecord(topic, partition, key, "");
given(sendResult.getRecordMetadata()).willReturn(recordMetadata);
given(sendResult.getProducerRecord()).willReturn(producerRecord);
when(template.send(any(), any())).thenReturn(responseFuture);
doAnswer(invocationOnMock -> {
ListenableFutureCallback listenableFutureCallback = invocationOnMock.getArgument(0);
listenableFutureCallback.onFailure(throwable);
return null;
})
.when(responseFuture).addCallback(any()); //this is the line that is throwing an error when trying to debug.
publisher.publishEventToTopic();
}
我不太确定那是什么意思,所以几个小时后,我决定尝试使用另一条路径-使用MockProducer类。似乎可行,但不一致:
@Test
public void test3() throws InterruptedException {
ListenableFuture<SendResult<String, KafkaRequest>> responseErrorFuture = mock(ListenableFuture.class);
MockProducer mockProducer = new MockProducer(Cluster.empty(), false, null, null, null);
mockProducer.clear();
mockProducer.errorNext(new RuntimeException("Offset commit failed on partition my-topic-2-9 at offset 0")); //this doesn't work anymore.
publisher.publishEventToTopic();
}
所以我尝试将其添加到其中,但是它抱怨我没有嘲笑正确的东西:
doAnswer(invocation -> {
ListenableFutureCallback listenableFutureCallback = invocation.getArgument(0);
mockProducer.errorNext(new RuntimeException("Offset commit failed on partition my-topic-2-9 at offset 0"));
return null;
}).when(mockProducer).send(any(), any());
我的问题是,当我发送Kafka请求时,是否有人对我做错了什么不知道测试回调的onFailure方法有什么想法?
谢谢!