[英]Mock kafka producer in jUnit to test Future(Java)
I am changing the implementation of how kafka sends events from async to sync我正在更改 kafka 如何将事件从异步发送到同步的实现
I found the following我发现了以下
producer.send(producerRecord, (m, e) -> {
...some login...
}).get();
} catch (InterruptedException | RuntimeException | ExecutionException e) {
logger.info("", e);
throw new RuntimeException(e);
}
I've added the get() method, which makes the code wait for a response before moving to the next one.我添加了 get() 方法,它使代码在移动到下一个之前等待响应。
I now want to create a jUnit test to test this but I'm struggling to do so I'm mocking the producer using Mockito Then I'm using the following code我现在想创建一个 jUnit 测试来测试它,但我正在努力这样做
KafkaProducer mockProducer = Mockito.mock(KafkaProducer.class);
Future<RecordMetadata> future = Mockito.mock(Future.class);
doReturn(future).when(mockProducer).send(any());
when(future.get()).thenThrow(InterruptedException.class);
communicator.sendEvent(eventValue);//sendEvent then calls the producer and sends an event
I'm getting NullPointerException for some reason but when I evaluate producer.sendEvent and also producer.sendEvent(producerRecord).get() in the debugger.由于某种原因,我得到了 NullPointerException,但是当我在调试器中评估 producer.sendEvent 和 producer.sendEvent(producerRecord).get() 时。 They both have values
他们都有价值观
So I'm not sure what's wrong.所以我不确定出了什么问题。
any advice will be appreciated任何建议将被认真考虑
You do not mock the method that you call later (as @kiuby_88 already mentioned in a comment).您不会模拟您稍后调用的方法(正如评论中已经提到的@kiuby_88)。
So you should do it in your test like this:所以你应该在你的测试中这样做:
KafkaProducer mockProducer = Mockito.mock(KafkaProducer.class);
Future<RecordMetadata> future = Mockito.mock(Future.class);
when(mockProducer).send(any(), any()).thenReturn(future);
when(future.get()).thenThrow(InterruptedException.class);
communicator.sendEvent(eventValue);
You mixed the doReturn
style of Mockito configurations with the when
style, which is confusing a bit.您将 Mockito 配置的
doReturn
样式与when
样式混合在一起,这有点令人困惑。 The doReturn
style was introduced for setting up reactions on the call of methods returning void
but can also be used to return values from other methods - but in my opinion it reduces confusion of the reader of you test-code, if you use one style throughout a whole test.引入了
doReturn
样式以设置对返回void
的方法调用的反应,但也可用于从其他方法返回值 - 但在我看来,如果您始终使用一种样式,它可以减少您的测试代码读者的混淆一个完整的测试。 An alternative style would be:另一种风格是:
doReturn(future).when(mockProducer).send(any(), any());
doThrow(InterruptedException.class).when(future).get();
See also the docs of Mockito about the doReturn()|doThrow()|另请参阅 Mockito 关于doReturn()|doThrow()|的文档doAnswer()|doNothing()|doCallRealMethod() family of methods
doAnswer()|doNothing()|doCallRealMethod() 系列方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.