问题
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