我想启动kafka测试容器并获取它的引导服务器:

@SpringBootTest
@ContextConfiguration(classes = {TestConfig.class, MyApplication.class}, initializers = MyIntegrationTest.Initializer.class)
@Testcontainers
public class MyIntegrationTest {

    @Container
    private static final KafkaContainer KAFKA = new KafkaContainer();

static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(@NotNull ConfigurableApplicationContext configurableApplicationContext) {
        TestPropertyValues values = TestPropertyValues.of(
            "spring.kafka.consumer.bootstrap-servers=" + KAFKA.getBootstrapServers(),
            "spring.producer.bootstrap-servers=" + KAFKA.getBootstrapServers()
        );
        values.applyTo(configurableApplicationContext);
    }
}


不幸的是我得到:

java.lang.IllegalStateException: You should start Kafka container first
at org.testcontainers.containers.KafkaContainer.getBootstrapServers(KafkaContainer.java:65) ~[kafka-1.12.2.jar:na]

最佳答案

唯一的问题是调用对象后调用start()方法

private static void startKafkaContainer() {

        KafkaContainer kafkaContainer = new KafkaContainer();
        kafkaContainer.start();

    }


更多信息请检查此repository

09-05 10:51