-
Notifications
You must be signed in to change notification settings - Fork 0
MockK : Testing the coroutines
Devrath edited this page Mar 2, 2024
·
2 revisions
- Coroutines involve code that executes asynchronously.
- Testing the
async
code requires code that can handle theasync
behavior.
- The
advanceTimeBy
function is used to simulate the passage of time and allow the coroutine to execute. In this case, the delay in the coroutine is 100 milliseconds, so we advance time by 100 milliseconds.
dependencies {
testImplementation "io.mockk:mockk:1.12.0"
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.5.0"
}
class CoroutineTestingDemo {
suspend fun suspendingFunctionDemo() = coroutineScope {
delay(100)
return@coroutineScope "Hello World!"
}
suspend fun coroutineLaunchDemo() = coroutineScope {
launch {
delay(100)
}
}
}
@OptIn(ExperimentalCoroutinesApi::class)
class CoroutineTestingDemoTest {
@Test
fun suspendingFunctionDemo() = runTest {
val mock = mockk<CoroutineTestingDemo>()
// Mocking a suspending function
coEvery { mock.suspendingFunctionDemo() } returns "Hello World!"
}
@Test
fun coroutineLaunchDemo() = runTest {
val mock = mockk<CoroutineTestingDemo>()
// Mocking a coroutine function
mock.coroutineLaunchDemo()
// Advance the time to make sure the coroutine executes
advanceTimeBy(100)
// Verify that the coroutine was launched
coVerify { mock.coroutineLaunchDemo() }
}
}