Search code examples
apache-kafkamicronauttestcontainers

Micronaut test change kafka port using testcontainers


I'm trying to run a Micronaut test including kafka with testcontainers.

For my test I need that my code and the kafka server share the same port but I can not configure the port in kafka:

@Container
static KafkaContainer kafka =
        new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));

It is generating a random port and it is not possible to configure it.

Another possibility is to change the application.yml property that the producer user for the kafka server but I can not find any solución also.

properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, configuration.kafkaUrl);

Solution

  • Your test class needs to implement TestPropertyProvider and override getProperties():

    @MicronautTest   
    class MySpec extends Specification implements TestPropertyProvider { 
    
        private static final Collection<Book> received = new ConcurrentLinkedDeque<>()
    
        static KafkaContainer kafka = new KafkaContainer(
                DockerImageName.parse('confluentinc/cp-kafka:latest')) 
    
    
        @Override
        Map<String, String> getProperties() {
            kafka.start()
            ['kafka.bootstrap.servers': kafka.bootstrapServers] 
        }
    
       // tests here
    
    

    See this official Micronaut guide for a detailed tutorial: https://guides.micronaut.io/latest/micronaut-kafka-gradle-groovy.html