【问题标题】:Kotlin Anonymous Function Parameter Unit TestingKotlin 匿名函数参数单元测试
【发布时间】:2016-06-27 04:51:59
【问题描述】:

根据Kotlin Unit Testing for Function Parameter and Object,我们可以测试函数变量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)

或者函数参数的内联(如上)不利于单元测试,因此应该避免?

【问题讨论】:

    标签: unit-testing mockito kotlin


    【解决方案1】:

    一段时间后发现测试它的方法是使用 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      相关资源
      最近更新 更多