Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable kafka connection from spring boot test?

I am using spring kafka to consume message from kafka topic, so I have a kafka consumer configuration class:

@Configuration
class KafkaConfiguration {
 // kafka consumer configurations
}

I have some JUnit tests which will load spring context with mockMvc to test my API, I don't want to test features related to kafka messaging, how can I stop kafka from consuming message only for JUnit tests? It keep failing because I don't have a kafka server at my local and CI environment.

Spring profile is not a very good option, because I will have to write code like:

@Configuration
@Profile("!unit-test")
class KafkaConfiguration {
  //kafka configuration
}

which I will end up with production code written only for testing purpose, not very clean, is there other way I can do to disable kafka for tests?

like image 594
Jakim Avatar asked Oct 22 '25 14:10

Jakim


1 Answers

Add @ConditionalOnProperty annotation on configuration class

Example:

@ConditionalOnProperty(value = "kafka.enable", havingValue = "true", matchIfMissing = true)

, and add application.properties file property kafka.enable=false

like image 78
Atabek Taganov Avatar answered Oct 25 '25 13:10

Atabek Taganov