kotlinmockingmockk

How to call a lambda callback with mockk


I create a mock of a class with mockk. On this mock I now call a method that gets a lambda as a parameter.

This lambda serves as a callback to deliver state changes of the callback to the caller of the method.

class ObjectToMock() {
    fun methodToCall(someValue: String?, observer: (State) -> Unit) {
        ...
    }
}

How do I configure the mock to call the passed lambda?


Solution

  • You can use answers:

    val objToMock: ObjectToMock = mockk()
    # here we set up the mock to always call the second arg as a function for any arguments passed
    every {  objToMock.methodToCall(any(), any())} answers {
        # alternatively: omit `invoke`
        secondArg<(String) -> Unit>().invoke("anything")
    }
    
    objToMock.methodToCall("firstArgumentString"){
        # the lambda is passed as a trailing lambda thus outside the parens
        println("invoked with $it")
    }
    

    Within the answers scope you can access firstArg, secondArg, …. To get the argument in the expected type you specify it as a generic argument (here: (String) -> Unit). Note that I explicitly used invoke here to make it more readable, it may also be omitted.