Last active
August 20, 2023 06:33
-
-
Save ProArun/c7c4055cbc81a5f420920da98983760e to your computer and use it in GitHub Desktop.
Coroutine unit test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Util(val dispatcher:CoroutineDispatcher){ | |
var globalArg = false | |
suspend fun getUserName(): AddressDetail(){ | |
CoroutineScope(dispatcher).launch{ | |
globalArg = true | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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