kotlinx-coroutines-test

Test utilities for kotlinx.coroutines.

This package provides testing utilities for effectively testing coroutines.

Using in your project

Add kotlinx-coroutines-test to your project test dependencies:

dependencies {
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.5.1'
}

Do not depend on this project in your main sources, all utilities are intended and designed to be used only from tests.

Dispatchers.Main Delegation

Dispatchers.setMain will override the Main dispatcher in test situations. This is helpful when you want to execute a test in situations where the platform Main dispatcher is not available, or you wish to replace Dispatchers.Main with a testing dispatcher.

Once you have this dependency in the runtime, ServiceLoader mechanism will overwrite Dispatchers.Main with a testable implementation.

You can override the Main implementation using setMain method with any CoroutineDispatcher implementation, e.g.:

class SomeTest {

private val mainThreadSurrogate = newSingleThreadContext("UI thread")

@Before
fun setUp() {
Dispatchers.setMain(mainThreadSurrogate)
}

@After
fun tearDown() {
Dispatchers.resetMain() // reset main dispatcher to the original Main dispatcher
mainThreadSurrogate.close()
}

@Test
fun testSomeUI() = runBlocking {
launch(Dispatchers.Main) { // Will be launched in the mainThreadSurrogate dispatcher
// ...
}
}
}

Calling setMain or resetMain immediately changes the Main dispatcher globally. The testable version of Dispatchers.Main installed by the ServiceLoader will delegate to the dispatcher provided by setMain.

runBlockingTest

To test regular suspend functions or coroutines started with launch or async use the runBlockingTest coroutine builder that provides extra test control to coroutines.

  1. Auto-advancing of time for regular suspend functions

  2. Explicit time control for testing multiple coroutines

  3. Eager execution of launch or async code blocks

  4. Pause, manually advance, and restart the execution of coroutines in a test

  5. Report uncaught exceptions as test failures

Testing regular suspend functions

To test regular suspend functions, which may have a delay, you can use the runBlockingTest builder to start a testing coroutine. Any calls to delay will automatically advance virtual time by the amount delayed.

Packages

kotlinx.coroutines.test
Link copied to clipboard