Bruno Pinho
Bruno Pinho

Reputation: 58

Best way to mock Kafka on junit test?

I have a spring boot application that uses a Kafka consumer and producer. All the configuration of Kafka is on the application.yml

spring:
    kafka:
        consumer:
            enable-auto-commit: true
            key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
            value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
            bootstrap-servers: kafka.dev-streams.svc.cluster.local:9092
            group-id: dev.client
        producer:
            bootstrap-servers: kafka-0.kafka-headless.dev-streams.svc.cluster.local:9092,kafka-1.kafka-headless.dev-streams.svc.cluster.local:9092,kafka-2.kafka-headless.dev-streams.svc.cluster.local:9092
            key-serializer: org.apache.kafka.common.serialization.StringSerializer
            value-serializer: org.apache.kafka.common.serialization.StringSerializer
            retries: 3

Example of one consumer:

        @KafkaListener(topics = { "${kafka.topic.internal.request}" })
        @Override
        public void processRequest(@Payload String message,
                        @Header(name = KafkaHeaders.RECEIVED_MESSAGE_KEY, required = false) String key) {
                super.processRequest(message, key);
        } 

How can i mock kafka to get some message on the consumer using a Junit test and not use the bootstrap-server ?

Upvotes: 3

Views: 14859

Answers (1)

Etay Ceder
Etay Ceder

Reputation: 168

You can use embedded Kafka it's in-memory Kafka broker that runs during the test. here some articles on how to use it:

Upvotes: 1

Related Questions