小编Sum*_*rma的帖子

如何使用 Mockito.mockStatic 在 kotlin android 中模拟静态方法

如何使用 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
    }
Run Code Online (Sandbox Code Playgroud)

我收到此异常:

org.mockito.exceptions.misusing.MissingMethodInvocationException: when() 需要一个参数,它必须是“对模拟的方法调用”。例如:when(mock.getArticles()).thenReturn(articles);

此外,出现此错误的原因可能是:

  1. 你存根:final/private/equals()/hashCode() 方法。这些方法不能被存根/验证。不支持在非公共父类上声明的模拟方法。
  2. 在 when() 中,您不会在模拟上调用方法,而是在其他对象上调用方法。

junit android unit-testing mockito kotlin

6
推荐指数
2
解决办法
1719
查看次数

标签 统计

android ×1

junit ×1

kotlin ×1

mockito ×1

unit-testing ×1