I have a simple class with a private field.
class EmployeeData {
private var employeeAge: Int = 0
fun getAge(): Int {
return 1 + 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())
}
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)
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.
In Android, there are a lot of frameworks used for mocking in unit testing, such as PowerMock, Mockito, EasyMock, etc. MockK is definitely a better alternative to other mocking frameworks for Kotlin, the official development language for Android. Its main philosophy is first-class support for Kotlin features.
Mocking frameworks supports relaxed mocks like mockk's relaxed. This helps in getting a minimal test setup ready for tests without having to provide mock implementations for all methods of the mocked object.
verify supports the same argument matchers as every , along with a few additional matchers. Inside the verification block (between the opening curly bracket { and closing curly bracket } ), you write the method you want to verify.
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."
More info can be found on these 2 Github issues:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With