问题描述
我用 mockk 创建了一个类的模拟.在这个模拟中,我现在调用一个将 lambda 作为参数的方法.
I create a mock of a class with mockk.On this mock I now call a method that gets a lambda as a parameter.
此 lambda 用作回调,将回调的状态更改传递给方法的调用者.
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) {
...
}
}
如何配置 mock 以调用传递的 lambda?
How do I configure the mock to call the passed lambda?
推荐答案
你可以使用 answers
:
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
}
在 answers
范围内,您可以访问 firstArg
、secondArg
等,并通过将其作为通用参数提供来获取预期类型.请注意,我在这里明确使用了 invoke
以使其更具可读性,也可以省略.
Within the answers
scope you can access firstArg
, secondArg
etc and get it in the expected type by providing it as a generic argument. Note that I explicitly used invoke
here to make it more readable, it may also be omitted.
这篇关于如何使用 mockk 调用 lambda 回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!