【发布时间】:2020-07-22 20:30:25
【问题描述】:
对于下面给定的代码,在 Kotlin 中,无法执行函数 forEach(或类似的函数,map、filter,等等...),因为 BarList 被模拟了。所以forEach 和亲戚的本机实现不会被调用。在互联网上搜索了一下后,我得到了这个:
public class BarList<E> extends AbstractList<E> implements OrderedBarCollection<E> {
//...
}
//...
val mockedList: BarList<Foo> = mockBarList()
val fooList = listOf(Foo())
`when`(mockedList.iterator()).thenReturn(fooList.iterator())
`when`(mockedList.size).thenReturn(fooList.size)
com.nhaarman.mockito_kotlin
.doCallRealMethod()
.`when`(mockedList)
.forEach(Mockito.any<Consumer<Foo>>()) //Attempt to call the Consumer.
mockedList.forEach { foo ->
//Not executing
}
我根据这个问题的答案在上面尝试了这个:https://stackoverflow.com/a/49407513/2430555
我也试过了:
com.nhaarman.mockito_kotlin.doCallRealMethod().`when`(mockedList).forEach(any())
但它导致:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 1 recorded:
//...
Kotlin 源码中forEach 的定义是:
public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit
我想我应该用匹配 action: (T) -> Unit 的东西替换 any(),但我不知道该怎么做。
如果需要,我不介意使用交互器,但我至少需要让forEach 按预期运行。大家能帮帮我吗?
问候,
佩德罗
【问题讨论】:
-
你为什么要嘲笑这份名单?你不能用你想测试的任何假数据创建一个列表的实例吗?
标签: kotlin mockito powermock robolectric mockito-kotlin