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

  • I suggest using answers here:

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

    You can access firstArg, secondArg, … within the answers scope. To receive those arguments in the expected type, you must specify them as generic arguments (here: (String) -> Unit). Please note that I explicitly used invoke here to make the code more readable, but it may also be omitted as the returned function type would also be callable directly:

    secondArg<(String) -> Unit>()("anything")