[FIXED] How to mock a private function in android test with MockK?

Issue

I can’t seem to mock private functions in android tests. I’m also using the all-open plugin for pre-P testing. On non-android tests it runs with no problems. I figured it should work on android too, because it’s marked on MockK-android. Is this not implemented or am I missing something obvious?

androidTestImplementation "io.mockk:mockk-android:1.8.7"

@OpenForTesting
class A {
    fun publicFun() = privateFun()
    private fun privateFun() {}
    protected fun protectedFun() {}
}

@Test
fun privateFunctionMock() {
    val spy = spyk<A>()
    val mock = mockk<A>()
    val a = A()

    val functions = a::class.functions // size -> 6
    val spyFunctions = spy::class.functions // size -> 5
    val mockFunctions = mock::class.functions // size -> 5

    every { spy["privateFun"]() } returns Unit

    a.publicFun()
}

Fails with Exception, because the private function is missing.
io.mockk.MockKException: can’t find function privateFun() for dynamic call

Solution

Subclassing is employed to create mocks and spies for pre-P android instrumented tests. That means basically private methods are skipped because it is not possible to inherit them. That way counters are not counting private methods.

Answered By – oleksiyp

Answer Checked By – Willingham (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published