如何使用MockProducer为Spring Kafka事务编写单元测试

hsgswve4  于 2023-04-29  发布在  Apache
关注(0)|答案(1)|浏览(277)

我使用Spring transaction支持设置了以下仅限生产者的transactions。

@Transactional
public boolean sendData(String topic, Data data) {
    //returns new ProducerRecord<>(topic, data)
    final ProducerRecord<String, Data> producerRecord = createRecord(topic, data);

    try {
        kafkaTemplate.send(producerRecord).get(10, TimeUnit.SECONDS);
    }
    catch (ExecutionException e) {
        log.error(data, e);
        return false;
    }
    catch (TimeoutException | InterruptedException e) {
        log.error(data, e);
        return false;
    }
    return true;
}

spring.kafka.producer.transaction-id-prefix=tx- #producer property

有没有一种方法可以使用MockProducer编写单元测试来覆盖成功的提交和失败的回滚场景?

编辑

我计划遵循这种提交和回滚的测试方法。

@Test
void testValueWhenSendOnTransactionalCommit() {
    MockProducer<String, Data> mockProducer = new MockProducer<>(true, new StringSerializer(), new JsonSerializer<>())

    var kafkaTemplate = //How to proceed with KafkaTemplate 
    //initTransaction() and beginTransaction()
    var record = kafkaTemplate.send(producerRecord); //Mock producerRecord

    assertTrue(mockProducer.history().isEmpty());
    //commitTransaction()
    assertTrue(mockProducer.history().size() == 1);
}
qij5mzcb

qij5mzcb1#

@TransactionalKafkaTemplateKafkaTransactionManager必须配置为相同的ProducerFactory。是的,您可以为提到的MockProducer实现一个。然后分别使用MockProducer API执行单元测试。请和我们分享一下,到目前为止你都做了哪些尝试。

相关问题