Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test for Kotlin lambda callback

Let's say we have the following function to test

fun loadData(dataId: Long, completion: (JsonElement?, Exception?) -> Unit) {
    underlayingApi.post(url = "some/rest/url",
            completion = { rawResult, exception ->
                val processedResult = processJson(rawResult)
                completion(processedResult, exception)
            })
}

It's clear to me how to mock, inject, stub and verify the calls to underlayingApi.

How to verify the result returned via completion(processedResult, exception)?

like image 615
Martin Mlostek Avatar asked Jan 11 '18 10:01

Martin Mlostek


1 Answers

To test the lambdas behavior, the underlayingApi has to be mocked where the lambda is invoked via the InvoactionOnMock object like this.

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

This leads to the invocation of the callback within the object under test. Now to check if the callback out of the object under test is working verify it like that.

    objUnderTest.loadData(id,
                          { json, exception ->
                              assert....
                          })
like image 52
Martin Mlostek Avatar answered Oct 19 '22 10:10

Martin Mlostek