Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kafka TestContainer tries to connect to wrong address

I am learning ho to test Spring Boot Kafka application with TestContainers. The test passes. However, in the beginning there are a lot of such messages:

2021-04-05 09:00:13.927  WARN 1864 --- [| adminclient-1] org.apache.kafka.clients.NetworkClient   : [AdminClient clientId=adminclient-1] Connection to node -1 (localhost/127.0.0.1:9092) could not be established. Broker may not be available.

Later, producer connects to valid bootstrap servers:

    bootstrap.servers = [PLAINTEXT://localhost:55015]

How could I avoid such errors? They increase test time.

Here is the code: https://github.com/aleksei17/springboot-kafka/blob/master/src/test/java/com/example/kafka/springbootkafka/TestContainersTest1.java

like image 786
Aleksei Avatar asked Sep 06 '25 03:09

Aleksei


1 Answers

I had the same problem, solved creating and application-test.yml with:

spring:
  kafka:
    bootstrap-servers: fake:1234

KafkaServerTestProvider.java:

@ActiveProfiles("test")
@Testcontainers
@Slf4j
public class KafkaServerTestProvider {
  public static final KafkaContainer KAFKA_CONTAINER =
      new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));

  public static class KafkaServerInitializer
      implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(final ConfigurableApplicationContext applicationContext) {
      KAFKA_CONTAINER.start();
      TestPropertyValues.of(
              "spring.kafka.bootstrap-servers=" + KAFKA_CONTAINER.getBootstrapServers())
          .applyTo(applicationContext.getEnvironment());

      log.info("Kafka for testing: {}", KAFKA_CONTAINER.getBootstrapServers());
    }
  }
}

and the test:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@ActiveProfiles("test")
@ContextConfiguration(
    initializers = {KafkaServerTestProvider.KafkaServerInitializer.class},
    classes = Application.class)
class SampleServiceTestIT {
  @Autowired SampleService sampleService;

  @Test
  void sendMessageTest() {
    sampleService.sendMessage(
        "sampletopic",
        SampleRequest.builder().email("[email protected]").name("name").surname("surname").build());
  }
}
like image 106
lzafra Avatar answered Sep 07 '25 19:09

lzafra