问题描述
我有一个 kotlin Android 应用.有一个函数可以从后端加载组合并将它们返回给回调:
I have a kotlin Android app. There is a function that loads compositions from the backend and returns them to a callback:
getCompositons(callback: (Array<Composition>) -> Unit)
如何使用 mockito 模拟回调.这样我就可以做这样的事情:
How can I mock the callback using mockito. So that I then can do something like this:
var callback = //mockito mock
getCompositons(callback)
verify(callback, timeout(10000)).apply()
我读到 lambda 与 java 类型函数匹配,因此我假设 apply 可能是调用的方法.也许我可以模拟一个函数并使用它?但是 Kotlin 函数接口似乎只有一种返回类型,没有参数.java.util.Function 表示未解析的引用函数.
I read that lambda are matched to the java type function and therefore I assume apply could be the method invoked. Maybe I could mock a function and use that? But the Kotlin function interface only seems to have one return type, no parameters. java.util.Function says unresolved reference function.
任何帮助表示赞赏.
推荐答案
这真的和 mocking 任何其他类型没有什么不同:
This is really no different to mocking any other type:
val callback = mock<(Array<Composition>) -> Unit>()
getCompositons(callback)
verify(callback)(any()) // Or verify(callback).invoke(any()) to be explicit
(如果您不知道它们,我正在使用 mockito-kotlin绑定在这里.)
这篇关于如何在 kotlin 中使用 mockito 模拟 lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!