How to mock a function

There's no way to mock top-level functions in the clasical sense. They are analogous to (and compiled to) static functions in Java, so when you want classical mocking, you should refrain using them.

What you can do, though, is abstract whatever external dependencies you top-level function has as parameters of functional types, and “inject” them in your tests:

fun sumWithRandom(   // normal parameter   num: Long,   // injected function dependency, default value corresponds to the standard behavior   randomInt: (Long, Long) -> Long = ::getRandomInt ): Long {   return num + randomInt(1, 10) }

Then, in your test you can say:

assertEquals(43, sumWithRandom(42, { min, max -> min}))

2 Likes