Mar*_*tek 12 java lambda unit-testing mockito kotlin
假设我们有以下功能要测试
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.
如何验证通过返回的结果 completion(processedResult, exception)?
要测试lambda行为,underlayingApi必须模拟通过这样的InvoactionOnMock对象调用lambda的行为。
    `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....
                          })
在马丁的答案的基础上,这是我不加棉绒警告的方法:
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
            })
}
| 归档时间: | 
 | 
| 查看次数: | 3795 次 | 
| 最近记录: |