问题
Dependencies:
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"
ViewModel:
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)
}
})
}
To test function handleCall:
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)
}
Result:
java.lang.IllegalArgumentException: Parameter specified as non-null is null: method doSomething, parameter result
Here
whenever(call.invoke()).thenReturn(Result.success(0))
did not work and always return null when call.invoke() is called.
来源:https://stackoverflow.com/questions/61097992/mocked-suspend-lambda-returns-null-in-mockito