DispatchersNA

Lightweight KMP library to simplify replacing real CoroutineDispatcher instances with TestDispatcher by passing around a DispatcherProvider instance through the CoroutineContext.
Examples
CoroutineContext inheritance
The library works by making the CoroutineContext of the runTest method contain a DispatcherContextElement which production code will look for. If it can't find the element in the current CoroutineContext real dispatchers will be used.
This means that it is important to structure your code in such a way that all scopes that are used or created during test execution inherit their CoroutineContext from the test, which should in any case be done because of structure concurrency rules.
Dispatcher Mapping
The library has uses a default mapping for mapping real dispatchers to either StandardTestDispatcher or UnconfinedTestDispatcher according to the following mapping table
This behavior can be overridden using an extension method on the DispatcherProvider interface that is part of the dispatchers-test artifact.
fun `my test`() = runTest {
dispatchers.setAll(::UnconfinedTestDispatcher)
dispatchers.set(DispatcherId.IO, ::UnconfinedTestDispatcher)
..
}
Dependencies
dependencies {
implementation("inc.dna.coroutines:dispatchers:<latest-version>")
testImplementation("inc.dna.coroutines:dispatchers-test:<latest-version>")
}
For KMP projects
kotlin {
sourceSets {
commonMain {
implementation("inc.dna.coroutines:dispatchers:<latest-version>")
}
commonTest {
implementation("inc.dna.coroutines:dispatchers-test:<latest-version>")
}
}
}
Lint Rules
The library ships lint rules which will flag the usages of the following types in favor of the equivalents from this library.
kotlinx.coroutines.Dispatchers
kotlinx.coroutines.test.runTest
kotlinx.coroutines.test.TestScope
Detekt Rules
To come
Detekt might be preferred over lint because it tends to run quicker so there will be detekt rules coming as well