Search code examples
spring-bootapache-kafkaspring-kafka

KafkaProperties bean not found in test


I have a problem with kafka, it is fine when I start the application but when I run tests it can not find bean KafkaProperties.

Description:

Parameter 1 of constructor in ***.session.config.KafkaConfig required a bean of type 'org.springframework.boot.autoconfigure.kafka.KafkaProperties' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.boot.autoconfigure.kafka.KafkaProperties' in your configuration.

When I start the application it injects KafkaProperties but during test it does not.

Test class begins with,

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = SessionController.class)
public class SessionControllerTest {

KafkaConfig,

@RequiredArgsConstructor
@Configuration
public class KafkaConfig {

    private final KafkaProducerProps kafkaProducerProps;
    private final KafkaProperties kafkaProperties;


    @Bean
    public ProducerFactory<String, SessionEvent> producerFactory() {
        Map<String, Object> configProps = new HashMap<>();
        configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProducerProps.getBootstrapServers());
        configProps.put(ProducerConfig.CLIENT_ID_CONFIG, kafkaProducerProps.getClientId());
        configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        configProps.put(
                AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG,
                kafkaProperties.getProperties().get(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG)
        );
        configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class);
        configProps.put(AbstractKafkaAvroSerDeConfig.AUTO_REGISTER_SCHEMAS, true);

        return new DefaultKafkaProducerFactory<>(configProps);
    }

    @Bean
    public KafkaTemplate<String, SessionEvent> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }

    @Bean
    public KafkaMessageSender kafkaMessageSender() {
        return new KafkaMessageSender(kafkaTemplate(), kafkaProducerProps.getDefaultTopic());
    }
}

test/../application.yml

spring:
  main:
    allow-bean-definition-overriding: true
  kafka:
    bootstrap-servers: ${KAFKA_BROKERS:server_ip:9092}
    client-id: ${KAFKA_CLIENT_ID:session-service}
    template:
      default-topic: ${KAFKA_TOPIC:topic_name}
    properties:
      schema.registry.url: ${KAFKA_REGISTRY_URL:kafka_registry_url/}

Thank you.


Solution

  • You need to use @SpringBootTest to get Boot's auto configuration goodness in test cases.