Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ahmedMubarak2024/0ade30734263eb812bb77db69964361f to your computer and use it in GitHub Desktop.
Save ahmedMubarak2024/0ade30734263eb812bb77db69964361f to your computer and use it in GitHub Desktop.
CoroutineRule To swap Dispatcher.Main with TestCoroutineDispatcher used in Unit Testing
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestWatcher
import org.junit.runner.Description
/**
* Sets the main coroutines dispatcher to a [TestCoroutineScope] for unit testing. A
* [TestCoroutineScope] provides control over the execution of coroutines.
*
* Declare it as a JUnit Rule:
*
* ```
* @get:Rule
* var mainCoroutineRule = MainCoroutineRule()
* ```
*
* Use it directly as a [TestCoroutineScope]:
*
* ```
* mainCoroutineRule.pauseDispatcher()
* ...
* mainCoroutineRule.resumeDispatcher()
* ...
* mainCoroutineRule.runBlockingTest { }
* ...
*
* ```
*/
@ExperimentalCoroutinesApi
class MainCoroutineRule(val dispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()) :
TestWatcher(),
TestCoroutineScope by TestCoroutineScope(dispatcher) {
override fun starting(description: Description?) {
super.starting(description)
Dispatchers.setMain(dispatcher)
}
override fun finished(description: Description?) {
super.finished(description)
cleanupTestCoroutines()
Dispatchers.resetMain()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment