Micronaut 测试使用 testcontainers 更改 kafka 端口

Micronaut test change kafka port using testcontainers

我正在尝试 运行 Micronaut 测试,包括带测试容器的 kafka。

对于我的测试,我需要我的代码和 kafka 服务器共享相同的端口,但我无法在 kafka 中配置端口:

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

它正在生成一个随机端口,无法对其进行配置。

另一种可能性是更改 kafka 服务器的生产者用户的 application.yml 属性 但我也找不到任何解决方案。

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

您的测试 class 需要实施 TestPropertyProvider 并覆盖 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

有关详细教程,请参阅官方 Micronaut 指南: https://guides.micronaut.io/latest/micronaut-kafka-gradle-groovy.html