如何使用Mockk调用Lambda回调

如何使用Mockk调用Lambda回调

本文介绍了如何使用Mockk调用Lambda回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用ockk创建一个类的模型.在此模拟上,我现在调用一个将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) {
        ...
    }
}

如何配置模拟以调用传递的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范围内,您可以访问firstArgsecondArg等,甚至可以通过将其作为通用参数提供来获得预期的类型.请注意,我使用invoke使其更具可读性,也可以将其作为带空括号的普通函数来调用.

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.

这篇关于如何使用Mockk调用Lambda回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:11