Testing Kotlin extension functions
This might seem obvious for many Kotlin programmers but I did not realize that extension functions are also applied to mocks. This means that if you have a class you can not instantiate for some reason, like the constructor is private and in another package, or the class is abstract, you can still test your extension functions by simply mocking it.
Let's say I have an extension function on the com.sun.java.swing.action.ActionManager
which returns true
when the action manager contains a save
action. (Yes it is a silly example I know).
1/** Returns true if the actionManager has a "save" action */
2fun ActionManager.canSave(): Boolean =
3 getAction("save") == null
Of course we want to test our extension function, but writing a complete subclass of ActionManager just to test the extension function would be silly. Instead you can simply mock it with mockk:
1import io.mockk.coEvery
2import io.mockk.mockk
3...
4@Test
5internal fun testCanSaveExtensionFunction() {
6 val mockActionManager: ActionManager = mockk()
7 coEvery { mockActionManager.getAction("save") } answers { mockk() }
8 assertEquals(true, mockActionManager.canSave())
9}
This test will not only run your extension function, but you can even verify that the extension function calls the correct functions on the extended class because mockk lets you check invocations.
It seems like a silly little tip, but I liked it so much when I found this out I thought I'd share it with you.
Hope to be more active on the blog again, until then happy coding!