Eugene Khyst
Eugene Khyst

Reputation: 10315

Disabling Kafka Listeners for a particular Spring Boot test

How to disable @KafkaListener instances in @SpringBootTest tests in applications with Spring Boot (2.2+) and Spring Kafka (2.4+)?

The goal is to disable Kafka listeners in particular tests, so that such tests can run without starting an embedded Kafka broker.

Upvotes: 7

Views: 8153

Answers (1)

Eugene Khyst
Eugene Khyst

Reputation: 10315

Spring Boot allows to exclude classes from scanning by creating custom TypeExcludeFilter.

To disable Kafka listeners, exclude all classes that have methods annotated with @KafkaListener or @KafkaHandler:

public class KafkaListenersTypeExcludeFilter extends TypeExcludeFilter {

  private static final String KAFKA_LISTENER = "org.springframework.kafka.annotation.KafkaListener";
  private static final String KAFKA_HANDLER = "org.springframework.kafka.annotation.KafkaHandler";

  @Override
  public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) {
    AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
    return annotationMetadata.hasAnnotatedMethods(KAFKA_LISTENER)
        || annotationMetadata.hasAnnotatedMethods(KAFKA_HANDLER);
  }

  @Override
  public boolean equals(Object o) {
    return o != null && getClass() == o.getClass();
  }

  @Override
  public int hashCode() {
    return 1;
  }
}

Annotate Spring Boot test with @TypeExcludeFilters with KafkaListenersTypeExcludeFilter as a value:

@RunWith(SpringRunner.class)
@SpringBootTest
@TypeExcludeFilters(KafkaListenersTypeExcludeFilter.class)
public class SampleSpringBootTest {
  //...
}

Spring Boot tests annotated with @TypeExcludeFilters(KafkaListenersTypeExcludeFilter.class) will not start Kafka listeners, so do not require a Kafka broker.

When there are only a few Kafka listener beans you can also mock the listener beans as suggested Deadpool in the comment

@RunWith(SpringRunner.class)
@SpringBootTest
@MockBean({
    SampleKafkaListener.class
})
public class SampleSpringBootTest {
  //...
}

Upvotes: 5

Related Questions