Reputation: 251
How to use Mockito.mockStatic for mocking static methods in kotlin android ?
This is my code:
class MyUtilClassTest {
@Test
fun testIsEnabled() {
Mockito.mockStatic(MyUtilClass::class.java, Mockito.CALLS_REAL_METHODS)
.use { mocked ->
mocked.`when`<Boolean> { MyUtilClass.isEnabled() }.thenReturn(true)
assertTrue(MyUtilClass.isEnabled())
}
}
}
object MyUtilClass {
fun isEnabled(): Boolean = false
}
I am getting this exception:
org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
- you stub either of: final/private/equals()/hashCode() methods. Those methods cannot be stubbed/verified. Mocking methods declared on non-public parent classes is not supported.
- inside when() you don't call method on mock but on some other object.
Upvotes: 16
Views: 12034
Reputation: 1943
If you annotate your function isEnabled
with @JvmStatic
, you won't get any error. As @Neige pointed out, static functions in Kotlin
are actually not static in bytecode
by default. Therefore, we need to mark our function with @JvmStatic
in order to generate additional static getter/setter
methods.
object MyUtilClass {
@JvmStatic
fun isEnabled(): Boolean = false
}
Upvotes: 7
Reputation: 2840
From the JVM point of view MyUtilClass.isEnabled()
is not a static class/function.
You can use Show Kotlin Bytecode
to understand what is behind
public final class MyUtilClass {
public static final MyUtilClass INSTANCE;
public final boolean isEnabled() {
return false;
}
private MyUtilClass() {
}
static {
MyUtilClass var0 = new MyUtilClass();
INSTANCE = var0;
}
}
Upvotes: 2