Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocktito ArgumentCaptor for Kotlin lambda with arguments

I am trying to test this on Kotlin:

verify(myInterface).doSomething(argumentCaptor.capture())
capture.value.invoke(0L)

Where doSomething is:

doSomething((Long) -> Unit)

How can I create an ArgumentCaptor for this? Right now I am doing this

inline fun <reified T : Any> argumentCaptor() = ArgumentCaptor.forClass(T::class.java)!!
    val captor = argumentCaptor<(Long) -> Unit>()

    verify(mainApiInterface!!).downloadUserProfilePicture(captor.capture())
    captor.value.invoke(0L)

But I am getting java.lang.IllegalStateException: captor.capture() must not be null

I also tried integrating mockito-kotlin but I get a PowerMockito error:

No instance field named "reported" could be found in the class hierarchy of org.mockito.internal.MockitoCore.

like image 448
Jesus Almaral - Hackaprende Avatar asked Oct 30 '22 13:10

Jesus Almaral - Hackaprende


1 Answers

Using mockito-kotlin like this seems to work:

    val myService = mock<MyInterface>()

    myService.doSomething {
        println(it)
    }

    verify(myService).doSomething(capture { function ->
        function.invoke(123)
    })

Edit: removed unnecessary argumentCaptor<(Long) -> Unit>().apply {} - it wasn't used

like image 144
James Bassett Avatar answered Nov 07 '22 20:11

James Bassett