Ely*_*lye 4 unit-testing mockito 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)
}
| 归档时间: | 
 | 
| 查看次数: | 1255 次 | 
| 最近记录: |