6

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?

orelzion
  • 2,452
  • 4
  • 30
  • 46

3 Answers3

3

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"))
}
Interkot
  • 697
  • 8
  • 10
2

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

Misha Akopov
  • 12,241
  • 27
  • 68
  • 82
  • 2
    Yes, sorry for not updating but I ended up accessing the private properties myself through reflection – orelzion Nov 25 '19 at 14:02
  • Ohhh, I see. It is sad to use reflection for such cases. But if you have no straightforward way of doing it, what can we do. I am happy you found "solution" – Misha Akopov Nov 25 '19 at 14:27
0

It should be

every {
viewModel getProperty "driverMapSnapshotMap"
} returns mock(DriverRemoteModel::class)
sasikumar
  • 12,540
  • 3
  • 28
  • 48