Skip to content

Instantly share code, notes, and snippets.

@ProArun
Last active August 20, 2023 06:33
Show Gist options
  • Save ProArun/c7c4055cbc81a5f420920da98983760e to your computer and use it in GitHub Desktop.
Save ProArun/c7c4055cbc81a5f420920da98983760e to your computer and use it in GitHub Desktop.
Coroutine unit test
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4"
class MainCoroutineRule : TestWatcher(){
//TestWatcher is class which is use to make JUnit rule.
val testDispatcher = StandardTestDispatcher()
override fun starting(discription: Description?){
super.starting(description)
Dispatchers.setMain(testDispatcher)
}
override fun finished(description: Description?){
super.finished(description)
Dispatchers.resetMain()
}
}
class Util(val dispatcher:CoroutineDispatcher){
var globalArg = false
suspend fun getUserName(): AddressDetail(){
CoroutineScope(dispatcher).launch{
globalArg = true
}
}
}
class UtilTest{
@get:Rule
val mainCoroutineRule = MainCoroutineRule()
@Test
fun testGetUser(){
val sut = Util(mainCoroutineRule.testDispatcher)
runtest{
sut.getAddressDetail()
//When we lounch a coroutine then this test dispatcher will
//add this scheduler on a qoue for scheduling but doesn't execute it.
//now its our responsibility to tell the testDispatcher to execute the coroutine.
//so below peice of code will execute the coroutine and hold the thread
//till all the coroutine will not get executed.
mainCoroutineRule.testDispatcher.scheduler.advanceUntilIdle()
Assert.assertEquals(expected:true, sut.globalArg)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment