spring-boot - 在 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
库的单元测试Kottest
,Jnit5
@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()]
理想情况下,我想断言回调..有什么方法可以实现这一点吗?
解决方案
推荐阅读
- php - Laravel 中间件导致用户随机注销
- c++ - 如何使用堆栈(push,pop,top)向后存储和输出字符串?
- flutter - 如何在颤振中使用默认系统映射?
- javascript - Vue:Nuxt:内容未显示在 nuxt-child 中
- anaconda - conda env 导出中包含什么构建信息?
- r - X %*% fixef(object) 中的错误:参数不一致
- html - 使用位置相对/绝对重叠内容
- python - Python - 为什么第二个 for 循环从第二行开始
- javascript - 如何使列表项的删除按钮起作用
- python-3.x - 如何使用海龟在 Python 中制作烟花