title: How to test that block is run on a CoroutineDispatcher if it's invoked via launch(dispatcher) {...}
body: <p>We've recently started using coroutines on our Android application. All's gone fine and dandy, until someone wrote something roughly equivalent to the following function:</p>
  
  <pre><code>fun example(dispatcher: CoroutineDispatcher, block: () -&gt; Unit) {
      launch(dispatcher) {
          block()
      }
  }
  </code></pre>
  
  <p>We'd like to write a test that verifies that <code>block</code> is executed using <code>dispatcher</code>.</p>
  
  <p>We've tried the following, but this doesn't work because we get a NullPointerException because <code>dispatcher.parentContext</code> is not mocked. I'm loathe to mock it, because we don't care what context it's executed in, just that it's executed:</p>
  
  <pre><code>@Test
  fun `test that doesn't work`() {
      val dispatcher: CoroutineDispatcher = mock()
      val block: () -&gt; Unit = mock()
  
      // fails here, specifically on the call to `launch` in example()
      example(dispatcher, block)
  
      val captor = argumentCaptor&lt;Runnable&gt;()
      verify(dispatcher).dispatch(any(), captor.capture())
      verify(block, never()).invoke()
  
      captor.firstArgument.run()
      verify(block).invoke()
  }
  </code></pre>
  
  <p>We've come upon this as an option, but it still doesn't feel right:</p>
  
  <pre><code>@Test
  fun `test that works but doesn't feel right`() {
      val executor: ExecutorService = mock()
      val block: () -&gt; Unit = mock()
  
      example(executor.asCoroutineDispatcher(), block)
  
      val captor = argumentCaptor&lt;Runnable&gt;()
      verify(executor).execute(captor.capture())
      verify(block, never()).invoke()
  
      captor.firstArgument.run()
      verify(block).invoke()
  }
  </code></pre>
  
  <p>Can anyone come up with anything better?</p>
  
  <p>EDIT:</p>
  
  <p>Notable dependencies are as follows:</p>
  
  <pre><code>com.nhaarman:mockito-kotlin:1.5.0
  org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.5
  junit:junit:4.12
  org.jetbrains.kotlin:kotlin-stdlib:1.2.30
  </code></pre>