Mock a private property

Jamie Dulaney picture Jamie Dulaney · Jul 13, 2018 · Viewed 7.1k times · Source

Lets say we have a class like this:

class Whatever {
    private var something = false

    fun aMethod(): Int {
        return if( something ) {
            1
        } else {
            0
        }
    }
}

According to the documentation, it looks like I should be able to do the following:

val classUnderTest = spyk(Whatever())

every { classUnderTest getProperty "something" } returns true

assertThat(classUnderTest.aMethod()).isEqualTo(1)

but instead I get the error: io.mockk.MockKException: Missing calls inside every { ... } block

I'm using mockk 1.8.5, kotlin 1.2.51

Answer

Vova Stelmashchuk picture Vova Stelmashchuk · Nov 15, 2018

Try to use answers instead of returns, like this:

val mock = spyk(MockCls(), recordPrivateCalls = true)

every { mock.property } answers { fieldValue }
every { mock getProperty "property" } propertyType Int::class answers { fieldValue + 6 }
every { mock setProperty "property" value any<Int>() } propertyType Int::class answers  { fieldValue += value }
every { mock.property = any() } propertyType Int::class answers {
  fieldValue = value + 1
} andThen {
  fieldValue = value - 1
}