Java Kotlin lambda回调的单元测试

Java Kotlin lambda回调的单元测试,java,unit-testing,lambda,kotlin,mockito,Java,Unit Testing,Lambda,Kotlin,Mockito,假设我们要测试以下函数 fun loadData(dataId: Long, completion: (JsonElement?, Exception?) -> Unit) { underlayingApi.post(url = "some/rest/url", completion = { rawResult, exception -> val processedResult = processJson(rawResu

假设我们要测试以下函数

fun loadData(dataId: Long, completion: (JsonElement?, Exception?) -> Unit) {
    underlayingApi.post(url = "some/rest/url",
            completion = { rawResult, exception ->
                val processedResult = processJson(rawResult)
                completion(processedResult, exception)
            })
}
我很清楚如何模拟、注入、存根和验证对
underlayingApi
的调用


如何验证通过完成返回的结果(processedResult,exception)要测试lambdas行为,必须模拟
底层API
,其中lambda是通过
InvoationOnMock
对象调用的

    `when`(underlayingApi.post(eq("some/rest/url"),
                               any())).thenAnswer {
        val argument = it.arguments[1]
        val completion = argument as ((rawResult: String?, exception: Exception?) -> Unit)
        completion.invoke("result", null)
    }
这将导致在测试对象内调用回调。现在,要检查被测对象的回调是否正常工作,请像这样进行验证

    objUnderTest.loadData(id,
                          { json, exception ->
                              assert....
                          })

基于Martin的回答,以下是我的方法,没有任何警告:

import com.nhaarman.mockito_kotlin.*

@Test
fun loadData() {
    val mockUnderlyingApi: UnderlayingApi = mock()
    val underTest = ClassBeingTested()
    underTest.underlayingApi = mockUnderlyingApi

    whenever(mockUnderlyingApi.post(eq("some/rest/url"), any())).thenAnswer {
        val completion = it.getArgument<((rawResult: String?, exception: Exception?) -> Unit)>(1)
        completion.invoke("result", null)
    }

    underTest.loadData(0L,
            { jsonElement, exception ->
                // Check whatever you need to check
                // on jsonElement an/or exception
            })
}
import com.nhaarman.mockito_kotlin*
@试验
fun loadData(){
val mockunderyingapi:UnderlayingApi=mock()
val underTest=ClassBeingTested()
underTest.underlayingApi=mockunderlayingapi
无论何时(mockunderyingapi.post(eq(“some/rest/url”),any())。然后回答{
val completion=it.getArgument Unit)>(1)
completion.invoke(“result”,null)
}
测试不足。负载数据(0升,
{jsonElement,异常->
//检查你需要检查的任何东西
//关于jsonElement和/或异常
})
}

使用此选项,您可能会收到“未经检查的投射”线头警告。为了防止这种情况,您可以使用
getArgument()
函数。例如:
val argument=it.getArgument Unit)>(1)
感谢您提供最重要的一行
import com.nhaarman.mockito_kotlin.
。这是github的库:。对于
2.1.0
版本,只需将导入更改为
import com.nhaarman.mockitokotlin2.*
any()抛出InvalidUseOfMatchersException