Mocktito ArgumentCaptor for Kotlin lambda with arg

2019-06-25 12:44发布

问题:

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.

回答1:

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