MockK spy on top-level private function in Kotlin

Viewed 7666

I need to verify if bar function is called or not using MockK library.

MyFile.kt

fun foo() {
    bar()
}

private fun bar() { ... }

How can I mock the 'bar' function?

I am trying the following.

@Test
fun test() {
    mockkStatic("com.mypkg.MyFileKt")

    every { bar() } returns Unit

    foo()

    verify(exactly = 1) { bar() }
}

This gives compile-time error: Cannot access 'bar': it is private in file.

It works fine if I make the bar function internal. Probably I will have to spy on it but cannot find an example to do that.

1 Answers

Although I don't think it's a good idea to mock private methods, since they should most likely be tested in conjunction with the method calling them, MockK does support this: https://mockk.io/#private-functions-mocking--dynamic-calls

So your code would look something like this:

class TheClass {
    fun foo() {
        bar()
    }

    private fun bar() {}
}

@Test
fun theTest() {

    val mock = spyk<TheClass>(recordPrivateCalls = true)
    every { mock["bar"]() } returns Unit

    mock.foo()

    verify(exactly = 1) { mock["bar"]() }
}
Related