Apache kafka 使用Kafka进行模拟单元测试-回调模拟生成器

Apache kafka 使用Kafka进行模拟单元测试-回调模拟生成器,apache-kafka,callback,future,spring-kafka,spring-kafka-test,Apache Kafka,Callback,Future,Spring Kafka,Spring Kafka Test,我想设置一些关于调用卡夫卡的测试。我的卡夫卡通话有以下回调设置,请参见下文: @Async // allows function to be async. the config also has to be set @Override public void publishEventToTopic() { ListenableFuture<SendResult<String, KafkaRequest>> future = kafkaTemplate.se

我想设置一些关于调用卡夫卡的测试。我的卡夫卡通话有以下回调设置,请参见下文:

@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");
            }
        });
}
我的问题是,当我发送卡夫卡请求时,有人知道我在测试回调的onFailure方法时做错了什么吗

谢谢

@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();
}
@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());