Kotlin lambda回调的单元测试

时间:2018-01-11 10:25:40

标签: java unit-testing lambda kotlin mockito

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

var first = {
  a: 1,
  b: 'someString'
};

var container = {
  first: first,

  second: Object.assign({
      c: 34,
      d: 'something else'
    },
    first
  )
}

console.log(container)

我很清楚如何模拟,注入,存根和验证对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 返回的结果?

2 个答案:

答案 0 :(得分:6)

要测试lambdas行为,必须模拟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....
                          })

答案 1 :(得分:4)

以马丁的回答为基础,这是我的做法,没有棉绒警告:

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