title: How to test Kotlin Coroutine actors
body: <p>I've implemented an actor like in the official <a href="https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/shared-mutable-state-and-concurrency.md#actors" rel="nofollow noreferrer">kotlinx.coroutines docs</a>. Now I have to test them inside of my instrumented tests, but I'm always getting </p>
  
  <pre><code>IllegalStateException: This job has not completed yet
  </code></pre>
  
  <p>Here's my test code:</p>
  
  <pre><code>@RunWith(AndroidJUnit4::class)
  @ExperimentalCoroutinesApi
  class ExampleInstrumentedTest {
  
      @Test
      fun testIncrease() = runBlockingTest {
          val counter = Counter()
          for (i in 0..10) {
              counter.increase()
          }
      }
  
      @Test
      fun testException() = runBlockingTest {
          val counter = Counter()
          try {
              for (i in 0..11) {
                  counter.increase()
              }
              Assert.fail()
          } catch (e: Exception) {
              // All good if the exception was thrown
          }
      }
  }
  </code></pre>
  
  <p>And here's the actor:</p>
  
  <pre><code>sealed class CounterMsg
  object IncCounter : CounterMsg()
  class GetCounter(val response: CompletableDeferred&lt;Int&gt;) : CounterMsg()
  
  class CounterActor {
      private val actor = GlobalScope.actor&lt;CounterMsg&gt; {
          var counter = 0
          for (msg in channel) {
              when (msg) {
                  is IncCounter -&gt; if (counter &lt; 10) counter++ else throw RuntimeException()
                  is GetCounter -&gt; msg.response.complete(counter)
              }
          }
      }
  
      suspend fun send(message: CounterMsg) = actor.send(message)
  }
  
  class Counter {
      private val actor = CounterActor()
      suspend fun increase() = actor.send(IncCounter)
  }
  </code></pre>
  
  <p>My dependencies:</p>
  
  <pre><code>implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.40"
  implementation "org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.3.0-M1"
  androidTestImplementation "androidx.test.ext:junit:1.1.1"
  androidTestImplementation "androidx.test:runner:1.2.0"
  androidTestImplementation "org.jetbrains.kotlin:kotlin-test:1.3.40"
  androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.0-M1"
  </code></pre>
  
  <p>I've already tried <code>GlobalScope.actor&lt;CounterMsg&gt;(Dispatchers.Unconfined)</code> which at least will turn the first test to green, but the exception test is still failing. </p>