Kotlin lambda 回调的单元测试

2022-09-02 13:12:58

假设我们有以下函数要测试

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)


答案 1

为了测试 lambdas 行为,必须模拟通过这样的对象调用 lambda 的位置。underlayingApiInvoactionOnMock

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

答案 2

基于马丁的答案,这是我的方法,没有棉绒警告:

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

推荐