0

I am trying to write unit test for kafka producer. But I get an error - Could not autowire. No beans of 'EmbeddedKafkaBroker' type found. in the line lateinit var embeddedKafkaBroker: EmbeddedKafkaBroker

Here is my code

@ActiveProfiles("test")
@EmbeddedKafka(
   partitions = 1,
   bootstrapServersProperty = "spring.kafka.bootstrap-servers",
   topics = arrayOf("someTopic"))
@SpringBootTest(
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
    properties = ["kafka.schema-registry.url=mock://mock"]
)
internal class KafkaProducerServiceTest {

   @Autowired
   lateinit var embeddedKafkaBroker: EmbeddedKafkaBroker // Error line - Could not autowire. No beans of 'EmbeddedKafkaBroker' type found.

   @Autowired
   lateinit var producer: KafkaProducerService<EventKey, EventValue>

   @Test
   fun send() {
     val mockKey = mockk<EventKey>(relaxed = true)
     val mockValue = mockk<EventValue>(relaxed = true)

     producer.send(mockKey, mockValue)
   }
}

I am not very sure what is the reason for this error.

ever alian
  • 1,028
  • 3
  • 15
  • 45
  • You dont need to wire that. See https://www.baeldung.com/spring-boot-kafka-testing – OneCricketeer Apr 12 '23 at 02:20
  • @OneCricketeer but I do not have a consumer written in my project. So to test the producer I need a consumer. The samples given has ´EmbeddedKafkaBroker´. – ever alian Apr 12 '23 at 06:39
  • Producer/consumer doesn't matter. My point is that you shouldn't need to `@Autowired` the broker field to use any client. Also see [Spring docs](https://docs.spring.io/spring-kafka/reference/html/#kafka-testing-embeddedkafka-annotation). Besides this, Kafka already has `MockProducer` class, so you don't need Spring functions at all. What you are doing is an **integration** test, not unit test – OneCricketeer Apr 12 '23 at 18:38

1 Answers1

0

this error is because you are using @SpringBootTest annotation to provide conflict for spring boot, remove this and your issues are solved, and use @RunWith from jUnit.

for more information, you can check this link https://docs.spring.io/spring-kafka/reference/html/#kafka-testing-embeddedkafka-annotation

helvete
  • 2,455
  • 13
  • 33
  • 37
Amirshk
  • 26
  • 4