How to mock lambda with mockito in kotlin

雨燕双飞 提交于 2020-06-27 07:26:14

问题


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)

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()

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.

Any help appreciated.


回答1:


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

(In case you weren't aware of them, I'm using the mockito-kotlin bindings here.)



来源:https://stackoverflow.com/questions/53306884/how-to-mock-lambda-with-mockito-in-kotlin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!