https://kotlinlang.org logo
#mockk
Title
# mockk
d

Davide Giuseppe Farella

02/28/2019, 7:26 AM
How to properly
mockk / verify
a lambda? Looks like
Copy code
val observer = mockk<(Int) -> Unit>() 
observer( 1) 
verify { observer( 1 ) }
Is not working. Tbh I didn't test exactly that code, I was trying within an Android LiveData, but replacing the mockk with a real lambda i can see right output printed in the console. Same with
spy
o

oleksiyp

02/28/2019, 7:27 AM
Hi
Lambda should be straightforward as in Kotlin lambda always implements interface
Can you please tell what error you face
d

Davide Giuseppe Farella

02/28/2019, 7:31 AM
This is my code:
Copy code
val liveData = MutableLiveData<Int>()
​
val observer = mockk<(Int) -> Unit>()
val lifecycleOwner = mockk<LifecycleOwner>( relaxed = true )
val lifecycle = LifecycleRegistry( lifecycleOwner )
​
lifecycle.handleLifecycleEvent( Lifecycle.Event.ON_RESUME )
liveData.observe( lifecycleOwner, observer )
liveData.value = 1
verify( exactly = 1 ) { observer( 1 ) }
verify
says
observer( 1 )
has not been called, but replacing the mock with
{ println( it ) }
I can see 1 printed in the console
I didn't try the snipped mentioned in the first post directly because I had to leave my pc, but I can't see why the result should be different 🙄 ( maybe I'm wrong )
2 Views