title: How to use kotlinx.coroutines.withTimeout in kotlinx.coroutines.test.runTest?
body: <p>I have a suspend function that makes a rest call to an external API that I want to timeout after 1 minute.</p>
  <pre class="lang-kotlin prettyprint-override"><code>suspend fun makeApiCallWithTimeout(): List&lt;ApiResponseData&gt; =
     withTimeout(1.minutes) {
        apiCall()
     }
          
  </code></pre>
  <p>I'm trying to test it with Junit5 and kotlinx.coroutines.test 1.6.0 like so:</p>
  <pre class="lang-kotlin prettyprint-override"><code>@Test
  fun `Test api call`() = runTest {
     val responseData = &quot;[]&quot;
     mockWebServer.enqueue(mockResponse(body = responseData)
     val result = sut.makeApiCallWithTimeout()
     advanceUntilIdle()
     assertEquals(0, result.size)
  }
  </code></pre>
  <p>Unfortunately, I'm getting errors that look like this:</p>
  <pre class="lang-kotlin prettyprint-override"><code>Timed out waiting for 60000 ms
  kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 60000 ms
      at app//kotlinx.coroutines.TimeoutKt.TimeoutCancellationException(Timeout.kt:184)
      at app//kotlinx.coroutines.TimeoutCoroutine.run(Timeout.kt:154)
      at app//kotlinx.coroutines.test.TestDispatcher.processEvent$kotlinx_coroutines_test(TestDispatcher.kt:23)
      at app//kotlinx.coroutines.test.TestCoroutineScheduler.tryRunNextTask(TestCoroutineScheduler.kt:95)
      at app//kotlinx.coroutines.test.TestCoroutineScheduler.advanceUntilIdle(TestCoroutineScheduler.kt:110)
      at app//kotlinx.coroutines.test.TestBuildersKt__TestBuildersKt.runTestCoroutine(TestBuilders.kt:212)
      at app//kotlinx.coroutines.test.TestBuildersKt.runTestCoroutine(Unknown Source)
      at app//kotlinx.coroutines.test.TestBuildersKt__TestBuildersKt$runTest$1$1.invokeSuspend(TestBuilders.kt:167)
      at app//kotlinx.coroutines.test.TestBuildersKt__TestBuildersKt$runTest$1$1.invoke(TestBuilders.kt)
      at app//kotlinx.coroutines.test.TestBuildersKt__TestBuildersKt$runTest$1$1.invoke(TestBuilders.kt)
      at app//kotlinx.coroutines.test.TestBuildersJvmKt$createTestResult$1.invokeSuspend(TestBuildersJvm.kt:13)
      (Coroutine boundary)
  </code></pre>
  <p>It seems that kotlinx.coroutines.test.runTest is advancing virtual time on the withTimeout without giving it any time to execute its body. See (<a href="https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-test/README.md#using-withtimeout-inside-runtest" rel="nofollow noreferrer">https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-test/README.md#using-withtimeout-inside-runtest</a>)</p>
  <p>Unfortunately, the documentation doesn't provide a way to get around this.</p>
  <p>Please advise on how to test this function using runTest.</p>