本文介绍了Mockito ArgumentCaptor用于Kotlin函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑一个将接口实现作为参数的函数,如下所示:
Consider a function that takes an interface implementation as an argument like this:
interface Callback {
fun done()
}
class SomeClass {
fun doSomeThing(callback: Callback) {
// do something
callback.done()
}
}
当我想测试此函数的调用者时,我可以做类似的事情
When I want to test the caller of this function, I can do something like
val captor = ArgumentCaptor.forClass(Callback::class)
Mockito.verify(someClass).doSomeThing(captor.capture())
要测试调用回调时另一个类的作用,我可以做
To test what the other class does when the callback is invoked, I can then do
captor.value.done()
问题:如果我用
fun doSomeThing(done: () -> Unit) {
// do something
done.invoke()
}
可以使用ArgumentCaptor做到这一点吗,我必须在ArgumentCaptor.forClass(???)
Can this be done with ArgumentCaptor and what class do I have to use in ArgumentCaptor.forClass(???)
推荐答案
我建议 nhaarman/mockito-kotlin:将Mockito与Kotlin结合使用
inline fun <reified T : Any> argumentCaptor() = ArgumentCaptor.forClass(T::class.java)
来源: mockito-kotlin/ArgumentCaptor.kt,网址为a6f860461233ba92c7730dd42b0faf9ba2ce9281·nhaarman/mockito-kotlin
例如:
val captor = argumentCaptor<() -> Unit>()
verify(someClass).doSomeThing(captor.capture())
或
val captor: () -> Unit = argumentCaptor()
verify(someClass).doSomeThing(captor.capture())
这篇关于Mockito ArgumentCaptor用于Kotlin函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!