函数内部的函数调用,无法通过Kotlinmockito验证

sqougxex  于 4个月前  发布在  Kotlin
关注(0)|答案(1)|浏览(88)

我们需要验证函数getTree()getFish()内部被调用了多少次。但是库不识别函数调用Wanted but not invoked: factory.getTree();

import org.junit.jupiter.api.Test
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify

class Testing {

    open class Factory {
        open fun getFish(): List<Int> {
            getTree()
            return listOf(1,2,3,4,5)
        }

        open fun getTree(): String {
            return "tree"
        }

    }

    @Test
    fun testFish() {
        val mockedFactory = mock<Factory> {
            on { getFish() } doReturn  listOf(5,6,7,8,9,10)
            on { getTree() } doReturn  "tree"
        }
        mockedFactory.getFish()

        verify(mockedFactory, times(1)).getTree()
    }

}

字符串
成功验证在函数内部调用函数的次数

57hvy0tb

57hvy0tb1#

这是因为getFish被模拟了。所以它不会被“真正”调用。一旦getFish被调用,它会立即返回listOf(5,6,7,8,9,10)并 * 跳过 * 它的实际代码逻辑。
我建议改变测试策略:如果你想测试工厂,不要模仿它。既然你对执行真实的代码感兴趣,就让它成为真实的对象。

class Testing {

    class Factory {
        fun getFish(): List<Int> {
            getTree()
            return listOf(1,2,3,4,5)
        }

        fun getTree(): String {
            return "tree"
        }
    }

    val factory = Factory()

    @Test
    fun testFish() {
        factory.getFish()
        verify(factory, times(1)).getTree()
    }
}

字符串
请记住,如果测试目标保持对不同实体的引用,则通常使用模拟对象。这些实体被模拟以返回所需的数据并封装其内部逻辑,让开发人员只测试所需的目标,而不必担心其他实体。

相关问题