Mock private 属性 with mockk 抛出异常

Mock private property with mockk throws an excpetion

我正在使用 mockk 在 kotlin 中进行测试。但我似乎无法覆盖间谍对象中的私有 属性。

我有这个对象

private val driverMapSnapshotMap: MutableMap<Int, SnapshotImage> = mutableMapOf()

在我使用

监视的 class 中
viewModel = spyk(DriverListViewModel(), recordPrivateCalls = true)

但是当我尝试用模拟值填充它时,出现错误

every {
    viewModel getProperty "driverMapSnapshotMap"
} returns(mapOf(1 to mockkClass(SnapshotImage::class)))

我得到的错误

io.mockk.MockKException: Missing calls inside every { ... } block.

有什么想法吗?

应该是

every {
viewModel getProperty "driverMapSnapshotMap"
} returns mock(DriverRemoteModel::class)

It is nearly impossible to mock private properties as they don't have getter methods attached. This is kind of Kotlin optimization and solution is major change.

这是为具有相同问题的问题打开的问题:

https://github.com/mockk/mockk/issues/263

这是一个访问 Mockk 中私有字段的解决方案,用于 类(对于对象,它甚至更简单)

 class SaySomething {
    private val prefix by lazy { "Here is what I have to say: "}

    fun say( phrase : String ) : String {
        return prefix+phrase;
    }
}

  @Before
fun setUp() = MockKAnnotations.init(this, relaxUnitFun = true)

 @Test
fun SaySomething_test() {

    mockkConstructor(SaySomething::class)
    every { anyConstructed<SaySomething>() getProperty "prefix" } propertyType String::class returns "I don't want to say anything, but still: "

    val ss = SaySomething()
    assertThat( ss.say("Life is short, make most of it"), containsString( "I don't want to say anything"))
}