title: How to test a function running a coroutine in an Android instrumented test?
body: <p>In my Android Kotlin project, I have a class, with a function running a coroutine, that I want to test using an instrumented test (not unit test).</p>
  
  <p>Here is what it looks like:</p>
  
  <pre class="lang-kotlin prettyprint-override"><code>class DemoClass
  {
      fun demo(liveData: MutableLiveData&lt;String&gt;)
      {
          CoroutineScope(IO).launch {
              val result = doStuff()
              withContext(Main) { liveData.value = result }
          }
      }
  }
  </code></pre>
  
  <p>In my instrumented test class, here is what I tried:</p>
  
  <pre class="lang-kotlin prettyprint-override"><code>@RunWith(AndroidJUnit4::class)
  class ExampleInstrumentedTest
  {
      @ExperimentalCoroutinesApi
      @Test
      fun testCoroutine() = runBlockingTest {
          val demoClass = DemoClass()
          val liveData = MutableLiveData&lt;String&gt;()
          demoClass.demo(liveData)
          assertEquals("demo", liveData.value)
      }
  }
  </code></pre>
  
  <p>Unfortunately, it's not working. It seems like <code>runBlockingTest {}</code> is only available for unit testing, not instrumented testing. Here is my error when I run the test:</p>
  
  <pre><code>java.lang.NoClassDefFoundError: Failed resolution of: Lkotlinx/coroutines/test/TestBuildersKt;
  </code></pre>
  
  <p>So how can I test <code>DemoClass.demo()</code> and the <code>liveData</code> value in an instrumented test?</p>
  
  <p>Thanks.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I also tried this:</p>
  
  <pre class="lang-kotlin prettyprint-override"><code>@ExperimentalCoroutinesApi
  @RunWith(AndroidJUnit4::class)
  class ExampleInstrumentedTest
  {
      private val testDispatcher = TestCoroutineDispatcher()
  
      @Before
      fun setup() {
          Dispatchers.setMain(testDispatcher)
      }
  
      @After
      fun tearDown() {
          Dispatchers.resetMain()
          testDispatcher.cleanupTestCoroutines()
      }
  
      @Test
      fun testCoroutine(): Unit = runBlocking {
          val demoClass = DemoClass()
          val liveData = MutableLiveData&lt;String&gt;()
          demoClass.demo(liveData)
          assertEquals("demo", liveData.value)
      }
  }
  </code></pre>
  
  <p>The test runs, but I got this:</p>
  
  <pre><code>java.lang.AssertionError: 
  Expected :demo
  Actual   :null
  </code></pre>