androidkotlinunit-testingmockingmockk

Android Unit Tests - Geocoder Mockk "Failed matching mocking signature for"


I'm trying to build some unit tests and mock the Geocoder API in Android.

I have the following function which I try to build a unit test against it:

@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private suspend fun Geocoder.getFromLocationApi33(
    latitude: Double,
    longitude: Double
) = suspendCancellableCoroutine { continuation ->
    this.getFromLocation(latitude, longitude, MAX_RESULTS) { addresses ->
        continuation.resumeWith(Result.success(addresses.firstOrNull()))
    }
}

And my unit test looks like this:

val geocoder = mockk<Geocoder>()
val addressSlot = slot<(MutableList<Address>) -> Unit>()
coEvery {
    geocoder.getFromLocation(0.0, 0.0, 1, capture(addressSlot))
}.answers {
    addressSlot.captured.invoke(mutableListOf())
}

But I get the following error in the logs for the coEvery lines:

Failed matching mocking signature for SignedCall(retValue=, isRetValueMock=true, retType=class kotlin.Unit, self=Geocoder(#5), method=getFromLocation(Double, Double, Int, GeocodeListener), args=[0.0, 0.0, 1, com.weatherxm.util.GeocoderCompatTest$1$2$2$3$1$1$$Lambda$314/0x000000010059eab8@73c3ceb5], invocationStr=Geocoder(#5).getFromLocation(0.0, 0.0, 1, com.weatherxm.util.GeocoderCompatTest$1$2$2$3$1$1$$Lambda$314/0x000000010059eab8@73c3ceb5)) left matchers: [slotCapture()]

Any ideas how to solve it?


Solution

  • You can have it as:

    val listenerSlot = slot<Geocoder.GeocodeListener>()
    val address = mockk<Address>()
    every {
        geocoder.getFromLocation(0.0, 0.0, 1, capture(listenerSlot))
    } answers {
        listenerSlot.captured.onGeocode(listOf(address))
    }
    
    // Your assertions