0

I have a data class A with a function as follows:

data class A(val a: String) {
  fun foo(b: String) = "$a, $b"
}

I attempt the following mock in my test:

fun `whatever`() {
  val spy = spyk<A>()
  every { spy.a } returns "Tree"
  assertThat(spy.foo("Snake")).isEqualTo("Tree Snake")
}

When I run a test written like this it fails with a NullPointerException on the line fun foo... in the data class.

Am I doing anything wrong or is this a bug in MockK?

4

1 回答 1

3

当我运行你的代码时,我得到了完全不同的结果。首先它抱怨没有默认构造函数。

然后我修复它以使用非默认构造函数并打印"abc Snake"

val spy = spyk(A("abc"))
every { spy.a } returns "Tree"
println(spy.foo("Snake"))

这是有原因的。Kotlin通过函数中a的字段访问属性。foo这似乎是一种优化。

getfield 调用

MockK 目前对此无能为力。转换getfield呼叫有以下票证:https ://github.com/mockk/mockk/issues/104

于 2018-10-04T04:02:07.937 回答