【问题标题】:How to mock Kotlin's List.forEach?如何模拟 Kotlin List.forEach?
【发布时间】: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) -&gt; Unit 的东西替换 any(),但我不知道该怎么做。 如果需要,我不介意使用交互器,但我至少需要让forEach 按预期运行。大家能帮帮我吗?

问候,

佩德罗

【问题讨论】:

标签: kotlin mockito powermock robolectric mockito-kotlin


【解决方案1】:

我认为你根本不能模拟扩展功能,虽然它们不是目标类的成员。

forEach 只是Iterable 的外部助手

在这种情况下,您仍然会在 fooList 上调用 Kotlin 的通常的 forEach。

而且我不明白模拟集合的动机是什么,尤其是用简单的 ArrayList (listOf) 替换模拟 OrderedBarCollection 的迭代器,这样做有什么要求?

【讨论】:

【解决方案2】:

解决方案是使用thenAnswer 而不是thenReturn 作为模拟列表。

`when`(mockedList.iterator()).thenAnswer { fooList.iterator() }

原因:

作者:托比亚斯·伯杰

迭代器只适用于遍历列表一次。所以 每次调用 iterator() 函数时,通常都会得到一个新的。 如果你用 thenReturn(messageList.iterator()) 模拟它,它会 只需在 messageList 上调用一次并重用该迭代器实例 每次您尝试为您的模拟获取一个。一旦你的第一个循环结束 这个迭代器完成了,它总是会说它没有更多的项目。 使用 thenAnswer,您可以定义一个供应商,每次您的 使用模拟函数,为每个调用提供一个新的迭代器(如 预计)

【讨论】:

    猜你喜欢
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 2021-03-05
    相关资源
    最近更新 更多