问题描述
我正在学习如何使用 TestContainers 测试 Spring Boot Kafka 应用程序。测试通过。但是,一开始有很多这样的消息:
for
稍后,生产者连接到有效的引导服务器:
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.
这是代码:https://github.com/aleksei17/springboot-kafka/blob/master/src/test/java/com/example/kafka/springbootkafka/TestContainersTest1.java
解决方法
我遇到了同样的问题,解决了创建和 application-test.yml 的问题:
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());
}
}
}
和测试:
@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("user@email.com").name("name").surname("surname").build());
}
}