如何使用jmockit模拟Kotlin中的顶级功能 [英] How to mock a top-level-function in kotlin with jmockit
本文介绍了如何使用jmockit模拟Kotlin中的顶级功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我下面有一个要测试的功能,请在名为"Utils.kt"的文件中声明
Assuming the I have a function to be test below, declare at the file named "Utils.kt"
//Utils.kt
fun doSomething() = 1
然后我们创建一个测试类进行测试
Then we create a test class to test it
//UtilsTest.kt
@RunWith(JMockit::class)
class UtilsTest {
@Test
fun testDoSomething() {
object : Expectation() {
init {
doSomething()
result = 2
}
}
assertEquals(2, doSomething())
}
}
我想模拟doSomething
,使其返回2
,但是它不起作用,实际结果是1
I want to mock doSomething
, make it return 2
, but it won't work, actual result is 1
是否有解决此问题的方法?
Is there any workaround for this purpose?
推荐答案
一种变通方法,在Java方面对其进行了模拟,因为您无法从Kotlin文件中引用UtilsKt
类.
A workaround mock it in Java side as you cannot reference the UtilsKt
class from Kotlin files.
@RunWith(JMockit.class)
public final class UtilsFromJavaTest {
@Test
public final void testDoSomething(@Mocked @NotNull final UtilsKt mock) {
new Expectations() {
{
UtilsKt.doSomething();
this.result = 2;
}
};
Assert.assertEquals(2, UtilsKt.doSomething());
}
}
这篇关于如何使用jmockit模拟Kotlin中的顶级功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文