You need to enable JavaScript to run this app. Spring Embedded Kafka测试报Mock零交互但Service方法实际触发问题排查
优惠活动
大模型
产品
解决方案
定价
更多

Spring Embedded Kafka测试报Mock零交互但Service方法实际触发问题排查

根本原因
  1. 测试上下文隔离冲突:@SpringBootTest会启动独立的Spring应用上下文,容器会自行创建Consumer、Service的实例用于Kafka监听逻辑;而你同时使用的@RunWith(MockitoJUnitRunner.class)是Mockito单独管理Mock对象,你用@Mock、@InjectMocks创建的实例和Spring容器中的实例完全无关,实际被Kafka调用的Consumer注入的是Spring容器中的Service实例,不是你用来验证的Mock对象,自然没有交互记录。
  2. 异步消费无等待逻辑:Kafka的消息发送、消费是异步流程,调用kafkaTemplate.send后立刻执行验证逻辑,此时消息还未被消费者拉取、处理,自然不会触发Service调用。
修复步骤
  • 移除@RunWith(MockitoJUnitRunner.class)、@Mock、@InjectMocks注解,改用Spring Boot Test原生的@MockBean注解,该注解会直接将Mock的Service实例替换到Spring上下文中,保证被Kafka调用的Consumer注入的就是你要验证的Mock对象。
  • 增加异步消费等待逻辑,推荐使用Awaitility工具做弹性超时等待,避免硬编码睡眠时间的稳定性问题。
依赖引入(使用Awaitility需要)

Maven依赖:

<dependency>
    <groupId>org.awaitility</groupId>
    <artifactId>awaitility</artifactId>
    <version>4.2.0</version>
    <scope>test</scope>
</dependency>
修正后的测试类代码
@SpringBootTest
@DirtiesContext
@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9092", "port=9092" })
class ConsumerTest {

  @MockBean
  private Service service;

  @Autowired
  private KafkaTemplate<String, String> kafkaTemplate;

  @Test
  public void givenEmbeddedKafkaBroker_whenExistsTemperatureMessageInTopic_thenMessageReceivedByConsumerAndServiceInvoked() 
    throws Exception {
      String message = "Hello";
      kafkaTemplate.send("topic", message);

      // 最多等待10秒,直到service.add方法被调用1次
      Awaitility.await()
          .atMost(Duration.ofSeconds(10))
          .untilAsserted(() -> Mockito.verify(service, Mockito.times(1)).add());
  }
}

如果不想引入Awaitility,也可以临时在send方法后加Thread.sleep(5000)等待消费完成,但该方式稳定性较低,不同环境可能需要调整等待时长。

内容的提问来源于stack exchange,提问作者kayla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 21:15:03