如何在 kotlin 中使用 mockito 模拟 lambda

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

任何帮助表示赞赏.

推荐答案

这真的和 mocking 任何其他类型没有什么不同:

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绑定在这里.)

更多推荐

如何在 kotlin 中使用 mockito 模拟 lambda

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

发布评论

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

>www.elefans.com

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