Skip to content

MockK : Testing the coroutines

Devrath edited this page Mar 2, 2024 · 2 revisions

About

  • Coroutines involve code that executes asynchronously.
  • Testing the async code requires code that can handle the async behavior.

Observation

  • 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 Needed

dependencies {
    testImplementation "io.mockk:mockk:1.12.0"
    testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.5.0"
}

Code

class CoroutineTestingDemo {

    suspend fun suspendingFunctionDemo() =  coroutineScope {
        delay(100)
        return@coroutineScope "Hello World!"
    }

    suspend fun coroutineLaunchDemo() =  coroutineScope {
        launch {
            delay(100)
        }
    }

}

Test

@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() }
    }

}