Add MainDispatcherRule to swap Dispatchers.Main with a TestDispatcher

This commit is contained in:
Wolf-Martell Montwé 2023-05-16 17:20:09 +02:00
parent 8376909043
commit 5f0a6437cf
No known key found for this signature in database
GPG key ID: 6D45B21512ACBF72

View file

@ -0,0 +1,23 @@
package app.k9mail.core.ui.compose.testing
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.TestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestWatcher
/**
* A JUnit rule that swaps the [Dispatchers.Main] dispatcher with a [TestDispatcher] for the duration of the test.
*/
class MainDispatcherRule(
val testDispatcher: TestDispatcher = UnconfinedTestDispatcher(),
) : TestWatcher() {
override fun starting(description: org.junit.runner.Description?) {
Dispatchers.setMain(testDispatcher)
}
override fun finished(description: org.junit.runner.Description?) {
Dispatchers.resetMain()
}
}