【发布时间】:2016-03-07 22:33:53
【问题描述】:
我正在使用 Context 来访问 WifiManager 和 BluetoothManager 等系统级服务。如何使用 Mockito 模拟这个 getApplicationContext()?
【问题讨论】:
标签: android bluetooth mockito android-wifi android-context
我正在使用 Context 来访问 WifiManager 和 BluetoothManager 等系统级服务。如何使用 Mockito 模拟这个 getApplicationContext()?
【问题讨论】:
标签: android bluetooth mockito android-wifi android-context
让我们看看下面的类:MockContext
如果您需要更多见解,请查看Official Testing Fundamentals 页面
【讨论】:
Context context = mock(Context.class);
【讨论】:
'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..
如果你想获取Kotlin和Mockito的上下文,可以通过以下方式进行:
mock(Context::class.java)
【讨论】: