KafkaListener 在 Spring Boot 测试中未触发

问题描述 投票:0回答:2

我有一个 Spring Boot 测试来检查 kafka 消费者是否监听特定主题中的消息。使用

@SpringBootTest
时会触发 kafka 监听器。但我只是不想加载所有类,我只提供了这样的监听器类
@SpringBootTest(classes={KafkaConsumerTest.class})

仅加载消费者类时,监听器已停止触发。我有什么遗漏的吗?

这是 KafkaTestConsumer 类

@Service
public class KafkaTestConsumer {
  private static final Logger LOGGER = LoggerFactory.getLogger(KafkaTestConsumer.class);

  private CountDownLatch latch = new CountDownLatch(1);

  private String payload;

  @KafkaListener(topics = {"topic"})
  public void receive(ConsumerRecord<?, ?> consumerRecord) {
    payload = consumerRecord.toString();
    latch.countDown();
  }

  public CountDownLatch getLatch() {
    return latch;
  }

  public void resetLatch() {
    latch = new CountDownLatch(1);
  }

  public String getPayload() {
    return payload;
  }

}
spring-boot apache-kafka spring-kafka spring-kafka-test testcontainers-junit5
2个回答
1
投票

很高兴看到您的

KafkaConsumerTest
是什么,但也许您只是用普通的
@Configuration
覆盖整个自动配置。

在文档中查看更多内容:https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing.spring-boot-applications.detecting-configuration

如果要自定义主要配置,可以使用嵌套的

@TestConfiguration
类。与使用嵌套
@Configuration
类代替应用程序的主要配置不同,除了应用程序的主要配置之外,还使用嵌套
@TestConfiguration
类。


0
投票

在我的例子中,原因是

spring.main.lazy-initialization
设置为
true
,这阻止了 KafkaListener 启动。

© www.soinside.com 2019 - 2024. All rights reserved.