如何检查@KafkaListener是否在集成测试中被调用? [英] How to check if @KafkaListener was invoked in integration test?
问题描述
我想为整个卡夫卡流程编写一个集成测试.
I would like to write an integration test for whole kafka flow.
在我的生产代码中,我有:
In my production code I have:
@KafkaListener(topics = "myTopic")
public void listen(@Payload String payload) {
log.debug("processing payload: '{}' ", payload);
// business logic here
}
在测试代码中,我使用KafkaProducer<String, String> producer;
将消息发送到特定主题.
In my test code I use KafkaProducer<String, String> producer;
to send messages to specific topic.
我想要一个钩子,该钩子表明已调用@KafkaListener
.
我可以在测试中插入一些延迟,但这是一种不好的做法,我想避免这种情况.
I would like to have a hook that would indicate that @KafkaListener
was called.
I could insert some delay into test but it's a bad practice and I want to avoid it.
还有什么更好的方法来等待@KafkaListener
被处理?
Is there any better way to wait for @KafkaListener
being processed?
推荐答案
如果侦听器调用某些服务,则可以为该服务注入一个模拟并验证其已被调用.
If your listener invokes some service, you can inject a mock for that service and verify it was called.
此外,您可以将侦听器包装在测试用例中,并添加倒计时锁存器.
Also, you can wrap your listener in the test case and add a count down latch.
例如,请参见此答案.
这篇关于如何检查@KafkaListener是否在集成测试中被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!