卡夫卡集成测试案例

时间:2020-07-29 18:05:19

标签: junit apache-kafka powermock powermockito spring-kafka-test

我对junit测试用例非常陌生,我想为kafka集成编写junit。 下面是我的代码

@EnableKafka
@Configuration
public class KafkaConfiguration {
    
    @Value("${bts_config}")
    private String bts_config;
        
    @Value("${grpname}")
    private String grpname;

    @Bean
    public ProducerFactory<String, String> producerFactory() throws URISyntaxException{
        Map<String, Object> config = new HashMap<>();
        config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bts_config);
        config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        config.put("security.protocol", "SSL");
        config.put("ssl.protocol", "SSL");
        
        config.put("ssl.truststore.location", "/dan/client.truststore.jks");
        config.put("ssl.endpoint.identification.algorithm", "https");
        return new DefaultKafkaProducerFactory(config);
    }

    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() throws URISyntaxException {
        return new KafkaTemplate<String, String>(producerFactory());
    }
}

在其他课程中,我有一个方法,其中将通过使用kafkaTemplate将消息发送到kafka

public void pushMsgsKafaka(String topicName, String msg) {
        ListenableFuture<SendResult<String, String>> future =  kafkaTemplate.send(topicName, msg);
        future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {

            @Override
            public void onSuccess(SendResult<String, String> result) {
                //success
            }

            @Override
            public void onFailure(Throwable ex) {
                LOGGER.error("Unable to send message=[" 
                         + msg + "] due to : " + ex.getMessage());
            }

        });
}

现在我想编写KafkaConfig (@EnableKafka, @Configuration)的测试用例和public void sendDataToKafka(String topicName, String msg)方法的测试用例

我对于编写junit测试用例非常陌生,有人可以帮我吗

1 个答案:

答案 0 :(得分:0)

您想在KafkaKonfig中测试什么?恕我直言,这是单元测试是多余的罕见示例之一。您要做的只是在那儿初始化bean。那么在这种情况下,什么价值单元测试可以为您带来好处?

关于将某些东西推送到Kafka,我会说您不会使用单元测试来完成它,而是宁愿编写和集成测试(IT)。通过单元测试,可以测试代码单元的内部逻辑。意思是不关心周围的环境。在您的情况下,Kafka是外部事物,因此在单元测试中,您可以对它进行模拟,而不是测试是否确实将消息推送到Kafka。您可能想看一下用于模拟(https://site.mockito.org)的Mockito框架。如果我对这种特殊情况了解得不是您想实现的,那么总的来说可能会有用。

如果您想测试消息是否确实发送到Kafka,则实际上是想编写IT而不是单元测试。 IT部门的“问题”部分是您实际上不想将消息推送到共享的Kafka实例,因为您的测试可能会干扰其他测试在同一Kafka实例上执行的操作(就像是数据库一样)。例如,如果您在计算机上运行测试,而其他人将在同一Kafka实例上运行同一测试,则结果可能会受到影响。因此,您可能想为您的IT运行嵌入式Kafka实例。 (同样,如果您想测试与数据库的交互,并且每次测试运行都需要一个单独的数据库实例,那将完全相同) 使用Spring之后,您可能需要查看Spring框架引入的嵌入式Kafka。在Internet上可以找到很多示例,例如: https://codenotfound.com/spring-kafka-embedded-unit-test-example.html

我相信您可以在不使用Spring依赖项的情况下嵌入Kafka实例。只是看一个例子。