0

I have a spring boot test to check if a kafka consumer listens for a message in specific topic. The kafka listener is triggered when using @SpringBootTest. But I just don't want to load all the classes and I only supplied the listener class like this @SpringBootTest(classes={KafkaConsumerTest.class}).

When only loading the consumer class, the listener has stopped to trigger. Is there something I am missing?

Here is the KafkaTestConsumer class

@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;
  }

}
tsadkan yitbarek
  • 1,360
  • 2
  • 11
  • 28

1 Answers1

1

It would be great to see what is your KafkaConsumerTest, but perhaps you just override the whole auto-configuration with a plain @Configuration.

See more in docs: https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing.spring-boot-applications.detecting-configuration

If you want to customize the primary configuration, you can use a nested @TestConfiguration class. Unlike a nested @Configuration class, which would be used instead of your application’s primary configuration, a nested @TestConfiguration class is used in addition to your application’s primary configuration.

Artem Bilan
  • 113,505
  • 11
  • 91
  • 118
  • The KafkaTestConsumer is just a simple kafka listener, No override configuration – tsadkan yitbarek Jul 27 '22 at 19:49
  • Incase, I have updated the question description – tsadkan yitbarek Jul 27 '22 at 19:50
  • Well, I asked about a `KafkaConsumerTest`, not `KafkaTestConsumer`. With the code `@SpringBootTest(classes={KafkaConsumerTest.class})` you override an auto-configuration and therefore nothing is going to start your consumer. – Artem Bilan Jul 27 '22 at 19:52
  • 2
    There's a bunch of infrastructure beans needed; just adding the listener class won't do anything, you need an `@Configuration` class with (at least) `@EnableKafka`. – Gary Russell Jul 27 '22 at 21:00
  • Thanks Artem, Adding @EnabledKafka from my Test Configuration does the trick. It turns out I disabled spring to auto configure kafka for me by just loading only my consumer class – tsadkan yitbarek Jul 28 '22 at 01:59
  • Correct. That’s what my answer tells: as long as you provide plain `@Configuration`, Spring Boot backs off – Artem Bilan Jul 28 '22 at 02:01
  • @GaryRussell You saved a ton of time. I was Struggling to figure this, `@EnableKafka` worked. – aravindaM Jul 19 '23 at 07:42