title: How to mock Kotlin's List.forEach?
body: <p>For the given code below, in Kotlin, it's not possible to execute the function <code>forEach</code> (or anything similar, <code>map</code>, <code>filter</code>, so on...) because <code>BarList </code> is mocked. So the native implementation of <code>forEach</code> and relatives are not being called. After a bit of search on the internet I came with this:</p>
  <pre class="lang-kotlin prettyprint-override"><code>public class BarList&lt;E&gt; extends AbstractList&lt;E&gt; implements OrderedBarCollection&lt;E&gt; { 
      //...
  }
  //...
  
  val mockedList: BarList&lt;Foo&gt; = 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&lt;Consumer&lt;Foo&gt;&gt;()) //Attempt to call the Consumer.
  
  mockedList.forEach { foo -&gt;
      //Not executing
  }
  
  </code></pre>
  <p><em>I tried this above based on the answer of this question: <a href="https://stackoverflow.com/a/49407513/2430555">https://stackoverflow.com/a/49407513/2430555</a></em></p>
  <p>I also tried:</p>
  <pre class="lang-kotlin prettyprint-override"><code>com.nhaarman.mockito_kotlin.doCallRealMethod().`when`(mockedList).forEach(any())
  </code></pre>
  <p>But it's causing:</p>
  <pre><code>org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
  Invalid use of argument matchers!
  0 matchers expected, 1 recorded:
  //...
  </code></pre>
  <p>The definition of <code>forEach</code> in the Kotlin source code is:</p>
  <pre class="lang-kotlin prettyprint-override"><code>public inline fun &lt;T&gt; Iterable&lt;T&gt;.forEach(action: (T) -&gt; Unit): Unit
  </code></pre>
  <p>I think I should replace <code>any()</code> with something that matches <code>action: (T) -&gt; Unit</code>, but I am not sure how to do this.
  I don't mind to use interactor if needed, but I need to at least make <code>forEach</code> run as expected. Could you guys please help me?</p>
  <p>Regards,</p>
  <p>Pedro</p>