Mocking extension function in Kotlin

后端 未结 4 1438
暗喜
暗喜 2021-02-19 01:19

How to mock Kotlin extension function using Mockito or PowerMock in tests? Since they are resolved statically should they be tested as static method calls or as non static?

4条回答
  •  滥情空心
    2021-02-19 01:35

    I think MockK can help you.

    It supports mocking extension functions too.

    You can use it to mock object-wide extensions:

    data class Obj(val value: Int)
    
    class Ext {
        fun Obj.extensionFunc() = value + 5
    }
    
    with(mockk()) {
        every {
            Obj(5).extensionFunc()
        } returns 11
    
        assertEquals(11, Obj(5).extensionFunc())
    
        verify {
            Obj(5).extensionFunc()
        }
    }
    

    If you extension is a module-wide, meaning that it is declared in a file (not inside class), you should mock it in this way:

    data class Obj(val value: Int)
    
    // declared in File.kt ("pkg" package)
    fun Obj.extensionFunc() = value + 5
    
    mockkStatic("pkg.FileKt")
    
    every {
        Obj(5).extensionFunc()
    } returns 11
    
    assertEquals(11, Obj(5).extensionFunc())
    
    verify {
        Obj(5).extensionFunc()
    }
    

    By adding mockkStatic("pkg.FileKt") line with the name of a package and file where extension is declared (pkg.File.kt in the example).

    More info can be found here: web site and github

提交回复
热议问题