0

How to verify that a top level (static) function was called in a test with MockK?

Simple approach like:

verify { someTopLevelFunction("some text") }

results in io.mockk.MockKException: can't find stub kotlin.Unit.

georgij
  • 2,054
  • 4
  • 27
  • 43

1 Answers1

0

You would mockk the same way you mockk extension functions https://mockk.io/#extension-functions

In practice generally:

mockkStatic(ClassNameWhereFunctionIsLocated::class)

verify {
    someTopLevelFunction("some text")
} 
Murph_Fish
  • 279
  • 2
  • 17
  • 2
    Would like to add, just to avoid future bugs, that when mocking static functions you should in general call `unmockAll()` in the `@After` tear-down method of your tests, otherwise it will stay mocked between tests and even test classes (which is usually not what you want) – Can_of_awe Jul 10 '22 at 04:14
  • The problem ist there is no class, the function is top level. But even if I do mockkStatic(:: someTopLevelFunction) its not working. – georgij Jul 11 '22 at 07:27
  • @georgij on the JVM there is _always_ a class, even if the function is top-level. The class name is the file name followed by "Kt". See https://kotlinlang.org/docs/java-to-kotlin-interop.html#package-level-functions (as well as the link provided in this answer which also shows you how to mock a top-level function) – k314159 Jul 11 '22 at 11:43
  • 1
    Ah, I need to replace this "pkg." with my full package, now I know. – georgij Jul 11 '22 at 16:01