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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With