Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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


1 Answers

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.

like image 119
oleksiyp Avatar answered Sep 15 '25 20:09

oleksiyp