繁体   English   中英

Kafka的Spring Boot:如何编写除kafka配置外的单元集成测试

[英]Spring Boot with Kafka : How to write unit Integration tests excluding kafka configuration

我在SpringBoot应用程序中使用spring-kafka依赖关系以使用Kafka。

一切正常,直到我的Kafka实例启动并运行,但是问题是我的单元和集成测试,它们在我的本地运行良好,但在我的部署管道中却没有运行( 这很明显,因为Application试图与Kafka实例连接[在我的构建管道中]在运行测试时找不到任何 ),因此最终出现以下错误:

[Consumer clientId=consumer-1, groupId=biz-web-group-test] Connection to node -1 
could not be established. Broker may not be available.

直到我有一个用@KafkaListener注释注释的方法时,这种情况才会发生

 @KafkaListener(topics = "${biz-web.kafka.message.topic.name}", groupId = "${biz-web.kafka.message.group.id}")
 public void listenToKafkaMessages(ConsumerRecord consumerRecord) {
        // Some Logic
 }

一旦我注释了//此注释,测试用例就可以正常工作。

有没有一种方法可以在运行单元/集成测试时排除与kafka相关的配置或此批注。

如前所述, spring-test-kafka是要在单元/集成测试中使用的库。

EmbeddedKafkaBroker :嵌入式Kafka经纪人和Zookeeper管理器。 此类打算在单元测试中使用。

EmbeddedKafkaTest.java

@RunWith(SpringRunner.class)
@SpringBootTest
@EmbeddedKafka(topics= {"test"},count=1,partitions=1)
public class EmbeddedKafkaTest {

    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    @Autowired
    private EmbeddedKafkaBroker embeddedKafka;

    private KafkaTemplate<Integer, String> kafkaTemplate;


    @Test
    public void testConsumer() {

        Map<String, Object> producerProps=KafkaTestUtils.producerProps(this.embeddedKafka);
        ProducerFactory<Integer, String> producerFactory = new DefaultKafkaProducerFactory<>(producerProps);
        this.kafkaTemplate = new KafkaTemplate<>(producerFactory);
        logger.info("embedded kafka ",embeddedKafka);
        kafkaTemplate.send("test", "hello");
         Map<String, Object> consumerProps = KafkaTestUtils.consumerProps("demo-group", "true", this.embeddedKafka);
        consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        ConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(consumerProps);
        Consumer<Integer, String> consumer = cf.createConsumer();
        this.embeddedKafka.consumeFromAnEmbeddedTopic(consumer, "test");
        ConsumerRecords<Integer, String> replies = KafkaTestUtils.getRecords(consumer);
        Assert.assertTrue(replies.count() == 1);
    }

}

但是,您也可以通过在KafkaAutoConfiguration中排除KafkaAutoConfiguration来忽略kafka处理注释。

注意 :仅当使用自动配置时,此选项才适用。 在自定义配置的情况下,请确保依赖关系松散耦合,以忽略依赖关系注入问题。

AppTestWithoutKafka.java

@RunWith(SpringRunner.class)
@SpringBootTest
@EnableAutoConfiguration(exclude=KafkaAutoConfiguration.class)
public class AppTestWithoutKafka {

    @Test
    public void contextLoads() {
        System.out.println("context loads");
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM