4

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

zabson
  • 614
  • 1
  • 10
  • 18

2 Answers2

3

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.

oleksiyp
  • 2,659
  • 19
  • 15
  • 1
    Thanks for this quick response. Is it a mistake on the https://mockk.io/ANDROID.html, marking "private function mocking" on pre-P android as supported? Thanks for MockK! – zabson Sep 25 '18 at 19:53
-3
InternalPlatformDsl.dynamicSet(autoBannerViewPagerMock, "mBannerList", list)
every { autoBannerViewPagerMock.invoke("loadCoverImage") withArguments listOf(any<Int>(), any<Int>(), any<ImageView>(), any<stMetaBanner>()) } returns Unit
Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36