如何在Kotlin中使用Mockito模拟Lambda

编程入门 行业动态 更新时间:2024-10-09 20:27:33
本文介绍了如何在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

本文发布于:2023-11-28 04:49:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641016.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Kotlin   Lambda   Mockito

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!