我具有以下接口的扩展功能:
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.
根据文档,对于模块宽扩展功能,您需要用于为扩展功能创建的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()
}
}
}
}