繁体   English   中英

Kotlin lambda回调的单元测试

[英]Unit test for Kotlin lambda callback

假设我们有以下功能要测试

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) 返回的结果 completion(processedResult, exception)

要测试的lambda行为,所述underlayingApi具有其中的λ是通过调用以被模拟InvoactionOnMock这样的对象。

    `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的回答,这是我没有lint警告的方法:

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
            })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM