假设我们有以下功能来测试
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行为,必须模拟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.... })