dimanche 21 mars 2021

Can't instantiate proxy for class kotlinx.coroutines.Deferred

I am learning Kotlin, and I have been referring 'Programming Kotlin' by Venkat Subramaniam. In the chapter about testing coroutines, below snippets of code have been provided.

import kotlinx.coroutines.*
suspend fun getAirportStatus(airportCodes: List<String>): List<Airport> =
    withContext(Dispatchers.IO) {
        Airport.sort(
        airportCodes.map { code -> async { Airport.getAirportData(code) } }
                .map { response -> response.await() })
}

The unit test for the above is written with KotlinTest and Mockk, as below.

"getAirportStatus calls getAirportData asynchronously" {
    mockkStatic("kotlinx.coroutines.BuildersKt__Builders_commonKt")
    coEvery {
        any<CoroutineScope>().async<Airport>(context = any(), block = captureCoroutine())
    } answers {
        CompletableDeferred(iad)
    }

    getAirportStatus(listOf("IAD")) shouldBe listOf(iad)
    
    coVerify {
        any<CoroutineScope>().async<Airport>(context = any(), block = any())
    }
}

When I run the test, however, I get the below error.

Can't instantiate proxy for class kotlinx.coroutines.Deferred
io.mockk.MockKException: Can't instantiate proxy for class kotlinx.coroutines.Deferred
  1. What causes the error? What does "Can't instantiate proxy" actually mean?
  2. It is mentioned earlier in the book 'suspend' method calls must be done in coroutine context in the unit test, i.e, within runBlocking{}. How come getAirportStatus() method, a suspend method, is called without a runBlocking. What influence does 'coEvery' has on this aspect?

Aucun commentaire:

Enregistrer un commentaire