Kotlin匿名功能参数单元测试

艾莉

根据功能参数和对象的Kotlin单元测试,我们可以测试功能变量funcParam,因为它是一个对象功能变量。

但是,如果代码是使用匿名/内联函数参数编写的(这是Kotlin的一项非常出色的功能,它可以使我们消除不必要的临时变量)...

class MyClass1(val myObject: MyObject, val myObject2: MyObject2) {
    fun myFunctionOne() {
        myObject.functionWithFuncParam{ 
            num: Int ->
            // Do something to be tested
            myObject2.println(num)
        }
    }
}

class MyObject () {
    fun functionWithFuncParam(funcParam: (Int) -> Unit) {
        funcParam(32)
    }
}

如何编写测试这部分代码的单元测试?

            num: Int ->
            // Do something to be tested
            myObject2.println(num)

还是内联函数参数(如上)对于单元测试不利,因此应避免?

艾莉

一段时间后发现测试方法是使用Argument Captor。

@Test
fun myTest() {
    val myClass1 = MyClass1(mockMyObject, mockMyObject2)
    val argCaptor = argumentCaptor<(Int) -> Unit>()
    val num = 1  //Any number to test

    myClass1.myFunctionOne()
    verify(mockMyObject).functionWithFuncParam(argCaptor.capture())
    argCaptor.value.invoke(num)

    // after that you could verify the content in the anonymous function call
    verify(mockMyObject2).println(num)
}

有关更多信息,请参阅https://medium.com/@elye.project/how-to-unit-test-kotlins-private-function-variable-893d8a16b73f#.1f3v5mkql

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章