0

I have Spring Boot Application with using spring-kafka and spring-kafka-test. I have below MessageProducer.

@Component
public class MessageProducer {
   private KafkaTemplate<String, String> kafkaTemplate;

   @Autowired
   public MessageProducer(KafkaTemplate<String, String> kafkaTemplate) {
       this.kafkaTemplate = kafkaTemplate;
   }

   public void sendMessage(String message, String topicName) {
       kafkaTemplate.send(topicName, message);
   }
}

I want to write Junit for above without any mocking the class. I tried with EmbeddedKafkaRule but I am not sure how to connect it to my application defined kafka broker so when I send message on topic, consumer (in which @kafkaLister is present) should pick the message and process it.

With EmbeddedKafkaRule I am also getting below error.

 [Producer clientId=producer-1] Connection to node 0 (localhost/192.168.0.24:57516) could not be established. Broker may not be available.

Can some one please let me know how to write a Junit for my kafka producer without mocking any classes and it should test with real classes.

ppb
  • 2,299
  • 4
  • 43
  • 75

1 Answers1

0

Yes, I tried with following implementation and it works for me. You may try this one. Kindly, let me know in case any further assistance required from my side.

import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.the.basic.tech.info.kafka.consumer.Receiver;
import com.the.basic.tech.info.kafka.producer.Sender;
import com.the.basic.tech.info.model.Employee;

@SpringBootApplication
public class SpringKafkaApplication implements CommandLineRunner {

    @Autowired
    Sender sndr;
    
    @Autowired
    Receiver rcvr;
    
  public static void main(String[] args) {
    SpringApplication.run(SpringKafkaApplication.class, args);
  }
  
    @Override
    public void run(String... arg0) throws Exception {
        Employee employee = new Employee("2121", "John", "Dept-A", "3000", "30", "California");
        sndr.send(employee);

        rcvr.getLatch().await(10000, TimeUnit.MILLISECONDS);
    }
}

Sample Project [Spring Boot + Spring Kafka with Zookeeper + JSON Serialization | Deserialization + Example] https://thebasictechinfo.com/java-8/spring-boot-spring-kafka-with-zookeeper-json-serialization-deserialization-example/

  • Hi Pankaj, thank you for your response. I was trying to use above solution but I am getting `org.junit.internal.runners.rules.ValidationError: The @ClassRule 'embeddedKafka' must implement TestRule.` this error – ppb Dec 06 '21 at 18:00
  • Could you please share your code's snap shot .. may be I can help you. – Pankaj Sharma Dec 08 '21 at 10:30