【问题标题】:How to mock Context using Mockito?如何使用 Mockito 模拟上下文?
【发布时间】:2016-03-07 22:33:53
【问题描述】:

我正在使用 Context 来访问 WifiManager 和 BluetoothManager 等系统级服务。如何使用 Mockito 模拟这个 getApplicationContext()?

【问题讨论】:

    标签: android bluetooth mockito android-wifi android-context


    【解决方案1】:

    让我们看看下面的类:MockContext

    如果您需要更多见解,请查看Official Testing Fundamentals 页面

    【讨论】:

    • 你能在你的答案中多加一点吗?
    【解决方案2】:
        Context context = mock(Context.class);
    

    【讨论】:

    • 看起来它不适用于较新版本的 Mockito。 Mockito 禁止模拟具有复杂合约或易于通过其他方式构建的类型。它抛出异常'context' is mocking 'class android.content.Context'. Don't mock android components, as they have lots of state and complex behavior - use the real thing. A Context can be obtained from ApplicationProvider.getApplicationContext() in Robolectric tests, or from InstrumentationRegistry in emulator tests..
    【解决方案3】:

    如果你想获取KotlinMockito的上下文,可以通过以下方式进行:

    mock(Context::class.java)
    

    【讨论】:

      猜你喜欢
      • 2012-05-30
      • 2015-12-28
      • 2016-05-08
      • 2012-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多