如何在Kotlin中使用Mockito模拟Lambda [英] How to mock lambda with mockito in kotlin

查看:95
本文介绍了如何在Kotlin中使用Mockito模拟Lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个kotlin Android应用程序.有一个函数可以从后端加载合成并将其返回给回调:

I have a kotlin Android app. There is a function that loads compositions from the backend and returns them to a callback:

getCompositons(callback: (Array<Composition>) -> Unit)

我该如何使用Mockito模拟回调.这样我就可以执行以下操作:

How can I mock the callback using mockito. So that I then can do something like this:

var callback = //mockito mock
getCompositons(callback) 
verify(callback, timeout(10000)).apply()

我读到lambda与java类型的函数匹配,因此我认为apply可能是调用的方法.也许我可以模拟一个函数并使用它?但是Kotlin函数接口似乎只有一种返回类型,没有参数. java.util.Function表示未解决的引用函数.

I read that lambda are matched to the java type function and therefore I assume apply could be the method invoked. Maybe I could mock a function and use that? But the Kotlin function interface only seems to have one return type, no parameters. java.util.Function says unresolved reference function.

任何帮助表示赞赏.

推荐答案

这与模拟其他任何类型完全没有区别:

This is really no different to mocking any other type:

val callback = mock<(Array<Composition>) -> Unit>()

getCompositons(callback)

verify(callback)(any())  // Or verify(callback).invoke(any()) to be explicit

(如果您不了解它们,我会使用 mockito-kotlin绑定在这里.)

(In case you weren't aware of them, I'm using the mockito-kotlin bindings here.)

这篇关于如何在Kotlin中使用Mockito模拟Lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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