Mockito ArgumentCaptor for Kotlin function

2019-02-02 05:11发布

问题:

Consider a function that takes an interface implementation as an argument like this:

interface Callback {
    fun done()
}

class SomeClass {        

    fun doSomeThing(callback: Callback) {

        // do something

        callback.done()

    }    
}

When I want to test the caller of this function, I can do something like

val captor = ArgumentCaptor.forClass(Callback::class)
Mockito.verify(someClass).doSomeThing(captor.capture())

To test what the other class does when the callback is invoked, I can then do

captor.value.done()

Question: How can I do the same if I replace the callback interface with a high order function like

fun doSomeThing(done: () -> Unit) {

    // do something

    done.invoke()

}

Can this be done with ArgumentCaptor and what class do I have to use in ArgumentCaptor.forClass(???)

回答1:

I recommend nhaarman/mockito-kotlin: Using Mockito with Kotlin

It solves this through an inline function with a reified type parameter:

inline fun <reified T : Any> argumentCaptor() = ArgumentCaptor.forClass(T::class.java)

Source: mockito-kotlin/ArgumentCaptor.kt at a6f860461233ba92c7730dd42b0faf9ba2ce9281 · nhaarman/mockito-kotlin

e.g.:

val captor = argumentCaptor<() -> Unit>()
verify(someClass).doSomeThing(captor.capture())

or

val captor: () -> Unit = argumentCaptor()
verify(someClass).doSomeThing(captor.capture())