tree: ee7b1ab06ea134ba71e6482aeec129e3defa6c36 [path history] [tgz]
  1. resources/
  2. src/
  3. test/
  4. build.gradle
  5. README.md
kotlinx-coroutines-test/README.md

Module kotlinx-coroutines-test

Test utilities for kotlinx.coroutines. Provides Dispatchers.setMain to override the Main dispatcher.

Using in your project

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

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

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

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 ... } } }