Kotlin Mocked suspend lambda在Mockito中返回null
依赖关系:Kotlin Mocked suspend lambda在Mockito中返回null,kotlin,mocking,mockito,junit5,Kotlin,Mocking,Mockito,Junit5,依赖关系: testImplementation "androidx.arch.core:core-testing:2.0.0" testImplementation 'org.mockito:mockito-core:3.3.0' testImplementation 'org.mockito:mockito-inline:2.8.47' testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0" fun <
testImplementation "androidx.arch.core:core-testing:2.0.0"
testImplementation 'org.mockito:mockito-core:3.3.0'
testImplementation 'org.mockito:mockito-inline:2.8.47'
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
fun <T : Any> doSomething(
result: Result<T>,
callback: Callback<T>? = null
) {
when (result.status) {
Result.Status.SUCCESS -> {
callback?.success(result.data)
}
Result.Status.ERROR -> {
callback?.error(result)
}
}
}
suspend fun <T : Any> handleCall(
call: suspend () -> Result<T>,
callback: Callback<T>? = null
) {
doSomething(call.invoke(), object : Callback<T> {
override fun success(t: T?) {
callback?.success(t)
}
override fun error(result: Result<T>) {
...
callback?.error(result)
}
})
}
fun testHandleCallSuccess() {
val call = mock<suspend () -> Result<Int>>()
val callback = Mockito.mock(Callback::class.java) as Callback<Int>
runBlocking {
whenever(call.invoke()).thenReturn(Result.success(0))
baseViewModel.handleCall(call, callback)
}
verify(callback).success(0)
}
视图模型:
testImplementation "androidx.arch.core:core-testing:2.0.0"
testImplementation 'org.mockito:mockito-core:3.3.0'
testImplementation 'org.mockito:mockito-inline:2.8.47'
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
fun <T : Any> doSomething(
result: Result<T>,
callback: Callback<T>? = null
) {
when (result.status) {
Result.Status.SUCCESS -> {
callback?.success(result.data)
}
Result.Status.ERROR -> {
callback?.error(result)
}
}
}
suspend fun <T : Any> handleCall(
call: suspend () -> Result<T>,
callback: Callback<T>? = null
) {
doSomething(call.invoke(), object : Callback<T> {
override fun success(t: T?) {
callback?.success(t)
}
override fun error(result: Result<T>) {
...
callback?.error(result)
}
})
}
fun testHandleCallSuccess() {
val call = mock<suspend () -> Result<Int>>()
val callback = Mockito.mock(Callback::class.java) as Callback<Int>
runBlocking {
whenever(call.invoke()).thenReturn(Result.success(0))
baseViewModel.handleCall(call, callback)
}
verify(callback).success(0)
}
调用调用.invoke()时,该函数不起作用,始终返回null。是否有理由使用
回调
而不是高阶函数?实际上,它可能是高阶函数。但我认为这在这个问题上无关紧要=)