如何在kafka中初始化kafka consumerrecords< string,string>进行测试

kzipqqlq  于 2021-06-07  发布在  Kafka
关注(0)|答案(1)|浏览(593)

我正在为kafka消费组件编写测试用例并进行模拟 kafkaConsumer.poll() 返回 ConsumerRecords<String,String> . 我想初始化 ConsumerRecords 在mock中使用,但是 ConsumerRecords 期待实际的Kafka主题,我没有在测试中。我认为一种方法是保留对象的序列化副本并反序列化以进行初始化 ConsumerRecords . 有没有其他方法可以达到同样的效果。

goqiplq2

goqiplq21#

下面是一些示例代码(kafka clients lib版本0.10.1.1):

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.consumer.OffsetResetStrategy;
import org.apache.kafka.common.TopicPartition;

...
        String topic = "MyTopic";
        Collection<TopicPartition> partitions = new ArrayList<TopicPartition>();
        Collection<String> topicsCollection = new ArrayList<String>();
        partitions.add(new TopicPartition(topic, 1));
        Map<TopicPartition, Long> partitionsBeginningMap = new HashMap<TopicPartition, Long>();
        Map<TopicPartition, Long> partitionsEndMap = new HashMap<TopicPartition, Long>();

        long records = 10;
        for (TopicPartition partition : partitions) {
            partitionsBeginningMap.put(partition, 0l);
            partitionsEndMap.put(partition, records);
            topicsCollection.add(partition.topic());
        }

        MockConsumer<String, MyObject> second = new MockConsumer<String, MyObject>(
                OffsetResetStrategy.EARLIEST);
        second.subscribe(topicsCollection);
        second.rebalance(partitions);       
        second.updateBeginningOffsets(partitionsBeginningMap);
        second.updateEndOffsets(partitionsEndMap);
        for (long i = 0; i < 10; i++) {
            MyObject value = Generator.generate();
            ConsumerRecord<String, MyObject> record = new ConsumerRecord<String, MyObject>(
                    topic, 1, i, null,value);
            second.addRecord(record);
        }
    ...

相关问题