Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock lambda with mockito in kotlin

Tags:

mockito

kotlin

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.

like image 516
findusl Avatar asked Nov 14 '18 18:11

findusl


2 Answers

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

like image 123
Oliver Charlesworth Avatar answered Nov 20 '22 05:11

Oliver Charlesworth


You can do that like this:

val function: Array<Composition>) -> Unit = {}
val callback = mock(function::class.java)

getCompositons(callback)

verify(callback)(any()) // or for example verifyNoInteractions(callback)

No extra libraries besides the standard mockito are needed

like image 4
Javier Mendonça Avatar answered Nov 20 '22 05:11

Javier Mendonça