【发布时间】:2020-12-10 15:19:47
【问题描述】:
如何使用 Mockito.mockStatic 在 kotlin android 中模拟静态方法?
这是我的代码:
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
}
我遇到了这个异常:
org.mockito.exceptions.misusing.MissingMethodInvocationException: when() 需要一个参数,该参数必须是“模拟方法调用”。 例如: when(mock.getArticles()).thenReturn(articles);
此外,出现此错误的原因可能是:
- 您存根以下任一方法:final/private/equals()/hashCode() 方法。 这些方法不能被存根/验证。 不支持在非公共父类上声明的模拟方法。
- 在 when() 中,您不会在 mock 上调用方法,而是在其他对象上调用方法。
【问题讨论】:
-
如果您的目标是模拟 Kotlin 对象,那么已经有了答案:stackoverflow.com/questions/37977320/…
标签: android unit-testing kotlin junit mockito