what would be the Kotlin equivalent to this Java code?

doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        Design design = new Design();
        GetDesign.Listener callback = (GetDesign.Listener) invocation.getArguments()[0];
        callback.onSuccess(design);
        return null;
    }
}).when(someRepository).getDesign(any(GetDesign.Listener.class));

[更新]在try 了几个选项之后,我终于用mockito-kotlin解决了这个问题.我认为这是实现doAnswer的最舒适的方式.语法几乎保持不变:

doAnswer {
    callback = it.arguments[0] as GetDesign.Listener
    callback.onSuccess(Design())
    null
}.whenever(someRepository).execute(any(GetDesign.Listener::class.java))

Complete code and build.gradle configuration can be found here

推荐答案

doAnswer {
    val design = Design()

    val callback = it.arguments[0] as GetDesign.Listener
    callback.onSuccess(design)

    null // or you can type return@doAnswer null

}.`when`(someRepository).getDesign(any(GetDesign.Listener::class.java))

Kotlin相关问答推荐

Jetpack Compose中的数字 Select 器问题

Kotlin中的增广赋值语句中的难以理解的错误

Rabin-Karp字符串匹配的实现(Rolling hash)

Flow.state In() 未从其来源接收新值

如何使用 Firebase 和 Kotlin 在文本 (Jetpack Compose) 中显示当前用户名?

Kotlin 中的密封和内部有什么区别?

在 Kotlin 中,我可以在集合上有一个条件构建器元素吗?

Kotlin 方法重载

创建首选项屏幕时找不到androidx.preference.PreferenceScreen

Kotlin - 覆盖方法中的 IllegalArgumentException

如何在 kotlin 的片段类中更改 ActionBar 标题?

runOnUiThread 没有调用

如何处理 Kotlin 中的异常?

Kotlin协程处理错误和实现

将ExpectedException与Kotlin一起使用

Kotlin中具有多个参数的绑定适配器

在 suspendCoroutine 块中调用挂起函数的适当方法是什么?

什么是 Kotlin 等价于 Class<?>

将字符串转换为HashMap的最简单方法

有没有办法在Kotlin中设置一个私有常量