无法捕获可变列表 Mockk

Cannot Capture Mutable List Mockk

编译 https://mockk.io/#capturing 中提到的此类代码时出现 Kotlin 错误。究竟是怎么回事?

class Foo{
   fun fx(parm: MutableList<Double>) {}
}

val foo = Foo()
val parm: MutableList<Double> = mutableListOf()

every { foo.fx(capture(parm)) }

下面写错了

Kotlin: Type mismatch: inferred type is Double but MutableList<Double> was expected

capture 函数需要一个 Slot - 当您想要捕获单个调用的参数时 - 或者 MutableList - 当试图捕获多个调用的参数时。两者都是 T 类型,其中 T 是参数的类型。这必须与 verify 一起使用,而不是与 every.

一起使用

因此您必须使用两种机制中的任何一种来捕获调用参数。

val param = slot<MutableList<Double>>()
verify { foo.fx(capture(param)) }

// or
val params = mutableListOf<MutableList<Double>>()
verify { foo.fx(capture(params)) }

此外,这仅适用于模拟对象。 因此,与其创建 Foo 类型的实际对象,不如创建它的模拟对象。

// set up the mock
val foo = mockk<foo>()
every { foo.func(any()) } just runs

// call the mocked function, most likely you want to do this indirectly instead
foo.fx(mutableListOf())

// assert that the function has been called
val slot = slot<MutableList<Double>>()
verify { foo.fx(capture(slot)) }
val param = slot.captuted

// assert what the function actually has been called with - this example uses "Hamkrest"
assertThat(param, hasSize(equalTo(0)))