How to call a lambda callback with mockk

心已入冬 提交于 2019-12-10 17:17:15

问题


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?


回答1:


You can use answers:

val otm: ObjectToMock = mockk()
every {  otm.methodToCall(any(), any())} answers {
    secondArg<(String) -> Unit>().invoke("anything")
}

otm.methodToCall("bla"){
    println("invoked with $it") //invoked with anything
}

Within the answers scope you can access firstArg, secondArg etc and even get the expected type by providing it as a generic parameter. Note that I used invoke to make it more readable, you can also invoke it as a normal function with empty parentheses.



来源:https://stackoverflow.com/questions/53673292/how-to-call-a-lambda-callback-with-mockk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!