Mocked suspend lambda returns null in Mockito

 ̄綄美尐妖づ 提交于 2020-05-14 04:04:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!