嘲笑私有财产与嘲笑引发

时间:2019-11-19 12:41:19

标签: kotlin mockk

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

我有这个对象

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

在我监视使用的班级中

viewModel = spyk(DriverListViewModel(), recordPrivateCalls = true)

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

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

我得到的错误

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

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

这是一个在 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"))
}

答案 1 :(得分:0)

应该是

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

答案 2 :(得分:0)

  

模拟私有属性几乎是不可能的,因为它们没有附加getter方法。这是Kotlin优化的一种,解决方案是主要的变化。

这里有同样的问题:

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