我需要一些帮助,为我的Java kafka消费者构建一个Junit测试用例。
我的原始源代码具有如下方法,并且需要为其创建单元测试用例。
public void processConsumerRecord(ConsumerRecords<String, GenericRecord> records, boolean isEventProcessed, boolean isOffsetCommitted,
int totalErrorCountFromSinkService, int totalErrorCount, Consumer<String, GenericRecord> consumer) {
...... }
我的Kafka消费者正在从kafka主题中提取消息,我需要能够以ConsumerRecords格式提供输入消息,但作为单元测试的一部分,我不是从kafka轮询消息,而是模拟来自原始kafka的消息主题并向Unit测试用例提供静态输入消息,测试上述方法如图所示。如何以形式创建模拟输入消息 ConsumerRecords&lt; String,GenericRecord&gt; ?
答案 0 :(得分:3)
您可以创建ConsumerRecord而不是像下面那样进行模拟 -
Map<TopicPartition, List<ConsumerRecord<Integer, String>>> records = new LinkedHashMap<>();
String topic = "topic";
records.put(new TopicPartition(topic, 0), new ArrayList<ConsumerRecord<Integer, String>>());
ConsumerRecord<Integer, String> record1 = new ConsumerRecord<>(topic, 1, 0, 0L, TimestampType.CREATE_TIME, 0L, 0, 0, 1, "value1");
ConsumerRecord<Integer, String> record2 = new ConsumerRecord<>(topic, 1, 1, 0L, TimestampType.CREATE_TIME, 0L, 0, 0, 2, "value2");
records.put(new TopicPartition(topic, 1), Arrays.asList(record1, record2));
records.put(new TopicPartition(topic, 2), new ArrayList<ConsumerRecord<Integer, String>>());
ConsumerRecords<Integer, String> consumerRecords = new ConsumerRecords<>(records);