2

我有一个 Kotlin 类(问题被简化为有一个基本示例),其中有一个testedMethod()我想测试交互的方法。

我想确保传递给正确的参数anotherMethod(),我的问题是参数不是一个,而是一个lambda 函数

我正在寻找 Kotlin 中的一个简单解决方案,它可能基于也可能不基于java 的这个解决方案

class TestedClass {

    fun testedMethod() {
        anotherMethod({ passedMethod() })
    }

    fun passedMethod() {}

    fun anotherMethod(lambdaParameter: () -> Unit) {
        // Does something with lambdaParameter
    }
}
4

2 回答 2

2

这是我最终使用的解决方案。

基本上,您创建一个spy测试类以能够验证其自己的方法,并使用它argumentCaptor来捕获传递的 lambda 并能够调用其中的内容。

import com.nhaarman.mockito_kotlin.argumentCaptor
import com.nhaarman.mockito_kotlin.spy
import com.nhaarman.mockito_kotlin.verify

@Test
fun lambdaParameterPassedIsCorrect() {
    val testedClass = TestedClass()
    val spyOfTestedClass = spy(testedClass)

    val captor = argumentCaptor<() -> Unit>()

    spyOfTestedClass.testedMethod()

    verify(spyOfTestedClass).anotherMethod(captor.capture())
    // Invoke the function passed as a parameter 
    // and then verify that the expected method was called
    val function = captor.firstValue
    function.invoke()
    verify(spyOfTestedClass).passedMethod()
}

我仍然会对更简单的解决方案感兴趣。

于 2018-04-04T14:04:44.650 回答
0

您可以使用具有“验证”功能的 mockito_kotlin 库。

  verify(TestedClass, times(1)).anotherMethod(eq(passedMethod))

验证类“TestedClass”的方法“anotherMethod”调用一次,参数等于“passedMethod”

于 2018-03-25T11:32:42.007 回答