2

我有一个接口的扩展功能,如下所示:

import javax.jms.ConnectionFactory

fun ConnectionFactory.foo() {
    println("do some stuff")
}

如何模拟函数 foo?

请注意,我在http://mockk.io/#extension-functions中看到了类和对象的方法,但它不起作用。我试过这个:

import io.mockk.classMockk
import io.mockk.every
import org.junit.Test
import javax.jms.ConnectionFactory

class ExtensionFunctionTest {
@Test
fun mockExtensionFunction() {
    val connectionFactory = classMockk(ConnectionFactory::class)
    every { connectionFactory.foo() } returns println("do other stuff")
    connectionFactory.foo()
}
}

它抛出异常:

io.mockk.MockKException: Missing calls inside every { ... } block.
4

1 回答 1

4

根据模块范围扩展功能的文档,您需要staticMock“隐藏”为扩展功能创建的类。这是一个示例(假设文件名为com/sample/extmockingtest/SampleTest.kt):

fun <T> Iterable<T>.foo(): String  = "do some stuff"

class ExtensionFunctionTest {
    @Test
    fun mockExtensionFunction() {
        val itMock = classMockk(Iterable::class);
        staticMockk("com.sample.extmockingtest.SampleTestKt").use {
            every {
                itMock.foo()
            } returns "do other stuff"

            assertEquals("do other stuff", itMock.foo())

            verify {
                itMock.foo()
            }
        }
    }
}
于 2018-04-26T17:28:53.790 回答