How do you Mockk a Kotlin top level function?

泪湿孤枕 提交于 2019-12-08 15:58:58

问题


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!"

回答1:


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.




回答2:


Building on @Sergey's answer:

You could have the actual implementation of the sayHello() function in a variable that's then the default value of a function parameter to sayHello().

This example works:

package tests

import io.mockk.every
import io.mockk.mockk
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test

val sayHelloKotlin = { "Hello Kotlin!" }
fun sayHello(producer: () -> String = sayHelloKotlin): String = producer()

class Tests {
    interface Producer {
        fun produce(): String
    }

    @Test
    fun `Top level mocking`() {
        val mock = mockk<Producer>()
        every { mock.produce() } returns "Hello Mockk"

        val actual = sayHello(mock::produce)
        Assertions.assertEquals(actual, "Hello Mockk")
    }
}

The problem with this is that you're changing production code just to cater for testing, and it feels contrived.



来源:https://stackoverflow.com/questions/52890871/how-do-you-mockk-a-kotlin-top-level-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!