Skip to content

Latest commit

 

History

History
54 lines (41 loc) · 1.89 KB

File metadata and controls

54 lines (41 loc) · 1.89 KB

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

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