Mockk 在 Kotlin 中嘲笑私有财产 [英] Mockk Mocking Private Properties in Kotlin
问题描述
我有一个带有私有字段的简单类.
I have a simple class with a private field.
class EmployeeData {
private var employeeAge: Int = 0
fun getAge(): Int {
return 1 + employeeAge
}
}
我正在尝试使用官方文档中的以下内容来测试此私有 employeeAge
I am trying to test this private employeeAge
with the following from official docs
@Test
fun testPrivateAge() {
val mock = spyk(EmployeeData())
every {
mock getProperty "employeeAge"
} propertyType Int::class answers { fieldValue + 6 }
every {
mock setProperty "employeeAge" value any<Int>()
} propertyType Int::class answers { fieldValue += value }
every { mock getProperty "employeeAge" } returns 33
every { mock setProperty "employeeAge" value less(5) } just Runs
assertEquals(10,mock.getAge())
}
我收到来自 MockK 的异常
I am receiving such exception from MockK
io.mockk.MockKException: Missing calls inside every { ... } block.
at io.mockk.impl.recording.states.StubbingState.checkMissingCalls(StubbingState.kt:14)
at io.mockk.impl.recording.states.StubbingState.recordingDone(StubbingState.kt:8)
任何关于我做错了什么的线索?官方文档建议对私有属性使用这种技术,但对我来说它不起作用,我正在使用最新版本的 MockK,它是 v1.10.0.
Any clue on what's I am doing wrong? Official docs suggest using such technique against private properties but for me it doesn't work and I'm using latest on this moment version of MockK which is v1.10.0.
尽管对于私有方法来说,它的作用就像一个魅力.我可以在这个逻辑中测试私有方法.
Though for private methods it is working like a charm. I am able to test the private method in this logic.
推荐答案
这是一些 Kotlin 优化的问题.根据 MockK 作者的简要解释".模拟私有属性几乎是不可能的,因为它们没有附加 getter 方法.这是一种 Kotlin 优化,解决方案是重大变化."
This is a problem with some Kotlin optimisations. According to MockK author "Brief explanation. It is nearly impossible to mock private properties as they don't have getter methods attached. This is kind of Kotlin optimisation and solution is major change."
可以在这两个 Github 问题上找到更多信息:
More info can be found on these 2 Github issues:
这篇关于Mockk 在 Kotlin 中嘲笑私有财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!