Mock private property with mockk throws an excpetion

与世无争的帅哥 提交于 2021-01-27 12:50:28

问题


I'm using mockk for my testing in kotlin. But I can't seem to override a private property in a spy object.

I have this object

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

in a class that I spy on using

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

But when I try to make it fill up with mock values I get an error

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

The error I get

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

Any thoughts?


回答1:


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.

Here is issue opened for that with the same problem:

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




回答2:


Here is a solution to access private fields in Mockk for classes( for objects it is even simpler )

 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"))
}



回答3:


It should be

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


来源:https://stackoverflow.com/questions/58934393/mock-private-property-with-mockk-throws-an-excpetion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!