gpt4 book ai didi

java - 什么是 Kotlin 函数类型的 Java 等价物?

转载 作者:行者123 更新时间:2023-11-29 08:32:07 28 4
gpt4 key购买 nike

我有 Kotlin 代码和 Java 测试代码。由于 KotlinMockito 不是最好的 friend ,我没有将测试代码迁移到 Kotlin

Kotlin 中,我有 block 类型的方法。例如:

open fun getProductInfo(resultListener: (List<Deal>)->Unit, errorListener: (Throwable)->Unit)
{
...
}

现在我想在 Java 测试中 stub 这个方法。这些类型的java等价物是什么?换句话说,我应该写什么来代替下面的 ???s:

doAnswer(invocation -> {
??? resultListener = (???) invocation.getArguments()[0];
// call back resultListener
return null;
}).when(api).getProductInfo(any(), any());

最佳答案

来自Kotlin in Action书:

The Kotlin standard library defines a series of interfaces, corresponding to different numbers of function arguments: Function0<R> (this function takes no arguments), Function1<P1, R> (this function takes one argument), and so on. Each interface defines a single invoke method, and calling it will execute the function.

在这种情况下,这两个函数都是Function1实例,因为它们是采用一个参数的函数:

Mockito.doAnswer(invocation -> {
Function1<List<Deal>, Unit> resultListener =
(Function1<List<Deal>, Unit>) invocation.getArguments()[0];
Function1<Throwable, Unit> errorListener =
(Function1<Throwable, Unit>) invocation.getArguments()[1];

resultListener.invoke(new ArrayList<>());

return null;
}).when(api).getProductInfo(any(), any());

另一方面,您可以尝试 mockito-kotlininline version使用 Mockito 也可以在 Kotlin 中编写测试。

关于java - 什么是 Kotlin 函数类型的 Java 等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47050723/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com