Solution: Testing Kotlin Coroutines

See the solution to the testing coroutines challenge.

We'll cover the following

Solution

There are two ways to start a coroutine:

  • To use TestCoroutineScheduler on coroutines, we should use a dispatcher that supports it. The standard option is StandardTestDispatcher.
val scheduler = TestCoroutineScheduler()
    val testDispatcher = StandardTestDispatcher(scheduler)

    CoroutineScope(testDispatcher).launch
  • StandardTestDispatcher creates TestCoroutineScheduler by default, so we do not need to do so explicitly. We can access it with the scheduler property.

The solution we will discuss is the use of the scheduler property.

Get hands-on with 1200+ tech skills courses.