Unit testing kotlin coroutines on Android with JUnit 5

Photo by Franck V. on Unsplash
Exception in thread "main @coroutine#1" java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used

JUnit 4

JUnit 4 rule that replaces Dispatchers.Main with TestCoroutineDispatcher

JUnit 5

JUnit 5 extension that replaces Dispatchers.Main with TestCoroutineDispatcher
Example unit test that uses CoroutinesTestExtension

Bonus: Power of time machine

coroutinesTestExtension.pauseDispatcher()
coroutinesTestExtension.resumeDispatcher()
coroutinesTestExtension.advanceTimeBy(delayTimeMillis)
coroutinesTestExtension
.advanceUntilIdle()

P.S.

testImplementation "org.junit.jupiter:junit-jupiter:$junit_jupiter_version"
// replace
import
org.junit.Test
// with
import org.junit.jupiter.api.Test

--

--

Self-Employed Senior Android Dev | https://romantikonov.com/

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store