我使用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);
}
1条答案
按热度按时间qij5mzcb1#
该
@Transactional
的KafkaTemplate
和KafkaTransactionManager
必须配置为相同的ProducerFactory
。是的,您可以为提到的MockProducer
实现一个。然后分别使用MockProducer
API执行单元测试。请和我们分享一下,到目前为止你都做了哪些尝试。