How to mock a top-level-function in kotlin with jmockit

旧街凉风 提交于 2019-12-24 09:47:45

问题


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())
    }
}

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?


回答1:


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());
    }

}



回答2:


Thanks to @aristotll, we can simply extends the workaround to make it more easier to use.

first, declare a java class that return the UtilsKt class

//TopLevelFunctionClass.java
public class TopLevelFunctionClass {
    public static Class<UtilsKt> getUtilsClass() {
        return UtilsKt.class
    }
}

then, mock this class in expectation using partial mock

//UtilsTest.kt
@RunWith(JMockit::class)
class UtilsTest {
    @Test
    fun testDoSomething() {
        object : Expectation(TopLevelFunctionClass.getUtilsClass()) {
            init {
                doSomething()
                result = 2
            }
        }

        assertEquals(2, doSomething())
    }
}


来源:https://stackoverflow.com/questions/47985836/how-to-mock-a-top-level-function-in-kotlin-with-jmockit

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