java – 模拟一个返回未来以抛出异常的方法

我正在使用Java和Mockito来模拟一些单元测试方法.我想在下面的代码中模拟生成器,以便我可以测试抛出异常时发送的日志消息.我试着模拟未来然而我得到的错误是future.get()方法不能被模拟,而RecordMetadata类是final并且不能被模拟.任何帮助将不胜感激.

以下示例中的生产者是KafkaProducer.

public void send(Log log){
  Future<RecordMetadata> future = producer.send(new ProducerRecord<(this.topic, record));
  try {
     RecordMetadata recordMetadata = send.get();
  } catch (InterruptedException e) {
     LOG.error("Sending the message to kafka was interrupted. "+e);
  }
}

解决方法:

Kafka提供了一个MockProducer课程,您可以将其注入课堂进行测试.您可以在JUnit @ Before-annotated安装方法中将类中的生产者设置为MockProducer的实例.从MockProducer的引用文档:

A mock of the producer interface you can use for testing code that uses Kafka.

By default this mock will synchronously complete each send call successfully. However it can be configured to allow the user to control the completion of the call and supply an optional error for the producer to throw.

您可以使用#errorNext方法提供要在测试方案中引发的异常.

上一篇:android – 你如何投射RuntimeEnvironment.application?


下一篇:春天 – 为什么Mockito没有被触发?