Kotlin 函数的 Mockito ArgumentCaptor [英] Mockito ArgumentCaptor for Kotlin function

查看:27
本文介绍了Kotlin 函数的 Mockito ArgumentCaptor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个将接口实现作为参数的函数,如下所示:

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

}

这可以用 ArgumentCaptor 完成吗?我必须在 ArgumentCaptor.forClass(???)

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

推荐答案

我推荐 nhaarman/mockito-kotlin:在 Kotlin 中使用 Mockito

它通过 内联函数reified 类型参数:

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

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

例如:

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

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

这篇关于Kotlin 函数的 Mockito ArgumentCaptor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆