我有一个接口的扩展功能,如下所示:
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.
答案 0 :(得分:1)
根据模块范围扩展功能的documentation,您需要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()
}
}
}
}