【发布时间】:2019-04-05 12:59:40
【问题描述】:
我有一个使用 Mockito 模拟的挂起函数,但它返回 null
两个项目都使用
'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.0'
示例 1
这是我的测试,其中模拟返回 null
@Test
fun `when gps not enabled observer is notified`() = runBlocking {
// arrange
`when`(suspendingLocationService.getCurrentLocation()).thenReturn(result) // <- when called this returns null
// act
presenter.onStartShopButtonClick()
// assert
verify(view).observer
verify(observer).onPrepareShop()
}
我的演示者中有以下实现
override suspend fun onStartShopButtonClick() {
val result = suspendingLocationService.getCurrentLocation() // <- in my test result is null!!!!!!
view?.apply {
observer?.onPrepareShop()
when {
result.hasGivenPermission == false -> observer?.onStartShop(StoreData(), APIError(APIError.ErrorType.NO_PERMISSION))
result.hasGPSEnabled == false -> observer?.onStartShop(StoreData(), APIError(APIError.ErrorType.GPS_NOT_ENABLED))
result.latitude != null && result.longitude != null ->
storeLocationService.getCurrentStore(result.latitude, result.longitude) { store, error ->
observer?.onStartShop(store, error)
}
}
}
}
但是我相信下面正在运行的非常相似的实现
示例 2
下面的测试确实通过了,正确的函数确实响应了一个产品
@Test
fun `suspending implementation updates label`() = runBlocking {
// arrange
`when`(suspendingProductProvider.getProduct("testString")).thenReturn(product)
// act
presenter.textChanged("testString")
// assert
verify(view).update(product.name)
}
这里是presenter的实现
override suspend fun textChanged(newText: String?) {
val product = suspendingNetworkProvider.getProduct(newText)
view?.update(product.name)
}
这是我正在模拟的界面
interface SuspendingProductProvider {
suspend fun getProduct(search: String?): Product
}
在第一个示例中我没有做的事情
【问题讨论】:
标签: junit kotlin mockito kotlinx.coroutines