首页 > 解决方案 > 在 Kotlin 中单元测试 ListenableFuture 回调

问题描述

我在 Spring Boot 中有一个这样的 Kafka 发布者。

@Component
class EventPublisher(private val kafkaTemplate: KafkaTemplate<String, Event>) {
    
    private val logger = LoggerFactory.getLogger(EventPublisher::class.java)

    fun publish(event: Event) {
        
        kafkaTemplate.send("topic", event.getId(), event).addCallback({
            println("Record pushed with Id ${it?.producerRecord?.value()?.getId()}")
        }, {
            logger.error("Failed to publish record with ID ${event.getId()} with Exception ${it.message}", it)
        })
    }
}

这是我使用Mockk库的单元测试KottestJnit5

@Test
fun `Can catch exception during publish message to Kafka`() {

    val future = SettableListenableFuture<SendResult<String, Event>>()
    future.setException(InterruptedException("Exception calling Kafka"))

    every { future.addCallback(any<SuccessCallback<SendResult<String, Event>>>(), any()) } throws InterruptedException("Exception calling Kafka")

    val kafkaTemplate = mockk<KafkaTemplate<String, Event>>()

    every { kafkaTemplate.send("test", any<Event>()) } returns future

    val publisher = TelemetryPublisher(kafkaTemplate, "test")

    shouldThrow<InterruptedException> {

        publisher.publish(Event("1", 1, 10)))
    }
}

但是我收到了这个错误

Failed matching mocking signature for

left matchers: [any(), any()]
io.mockk.MockKException: Failed matching mocking signature for

left matchers: [any(), any()]

理想情况下,我想断言回调..有什么方法可以实现这一点吗?

标签: spring-bootkotlinspring-kafkamockkspring-kafka-test

解决方案


推荐阅读