How do you Mockk a Kotlin top level function?

Niel de Wet picture Niel de Wet · Oct 19, 2018 · Viewed 7.1k times · Source

Mockk allows mocking static functions, but how does one mock a Kotlin top level function?

For example, if I have a Kotlin file called HelloWorld.kt, how do I mock the sayHello() function?


HelloWorld.kt

fun sayHello() = "Hello Kotlin!"

Answer

oleksiyp picture oleksiyp · Oct 19, 2018

There is way to mockk a top level function:

mockkStatic("pkg.FileKt")
every { fun() } returns 5

You just need to know which file this function goes. Check in JAR or stack trace.