Android 单元测试 - Geocoder Mockk“无法匹配模拟签名”

问题描述 投票:0回答:1

我正在尝试构建一些单元测试并模拟 Android 中的 Geocoder API。

我有以下函数,我尝试针对它构建单元测试:

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

我的单元测试如下所示:

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

但是我在

coEvery
行的日志中收到以下错误:

SignedCall 的模拟签名匹配失败(retValue=, isRetValueMock=true, retType=class kotlin.Unit, self=Geocoder(#5), 方法=getFromLocation(Double, Double, Int, GeocodeListener), 参数=[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)) 左匹配器:[slotCapture()]

有什么想法可以解决吗?

android kotlin unit-testing mocking mockk
1个回答
0
投票

您可以将其作为:

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
© www.soinside.com 2019 - 2024. All rights reserved.