5

As per Kotlin Unit Testing for Function Parameter and Object, we could test the function variable funcParam, as it is an object function variable.

However if code is written using anonymous/inlining function parameter (which is a very nice Kotlin feature, that allow us to eliminate unnecessary temp variable for it)...

class MyClass1(val myObject: MyObject, val myObject2: MyObject2) {
    fun myFunctionOne() {
        myObject.functionWithFuncParam{ 
            num: Int ->
            // Do something to be tested
            myObject2.println(num)
        }
    }
}

class MyObject () {
    fun functionWithFuncParam(funcParam: (Int) -> Unit) {
        funcParam(32)
    }
}

How to write my unit test that test this part of code?

            num: Int ->
            // Do something to be tested
            myObject2.println(num)

Or the inlining of the function parameter (as above) is something not good for unit testing, and hence should be avoided?

Community
  • 1
  • 1
Elye
  • 53,639
  • 54
  • 212
  • 474

1 Answers1

7

After a while discover the way to test it is to use Argument Captor.

@Test
fun myTest() {
    val myClass1 = MyClass1(mockMyObject, mockMyObject2)
    val argCaptor = argumentCaptor<(Int) -> Unit>()
    val num = 1  //Any number to test

    myClass1.myFunctionOne()
    verify(mockMyObject).functionWithFuncParam(argCaptor.capture())
    argCaptor.value.invoke(num)

    // after that you could verify the content in the anonymous function call
    verify(mockMyObject2).println(num)
}

For more info, refer to https://medium.com/@elye.project/how-to-unit-test-kotlins-private-function-variable-893d8a16b73f#.1f3v5mkql

Elye
  • 53,639
  • 54
  • 212
  • 474