如何使用Mockito2在java / androidTest下模拟最终分类? [英] How to mock Final Clases under java/androidTest using Mockito2?
问题描述
当我在gradle中定义时,可以在java / test下模拟最终类:
Final classes can be mocked under java/test when I define in gradle:
testCompile org.mockito:mockito-inline:+
testCompile "org.mockito:mockito-inline:+"
如何在java / androidTest下模拟最终类?此解决方案不起作用:
How to mock final classes under java/androidTest? This solution does not work:
androidTestCompile org.mockito:mockito-android:+
androidTestCompile "org.mockito:mockito-android:+"
您有任何想法吗?
推荐答案
不支持模拟最终课程根据此GitHub问题 mockito-android
/ a>。
Mocking final classes is not supported for mockito-android
as per this GitHub issue.
从一位图书馆维护者那里:
From one of the library maintainers:
有目前尚无法使[模拟最终课程]在Android中正常运行,因为它缺少我们要基于其运行的工具API。 Android VM不是标准VM,仅实现Java规范的子集。只要Google不选择扩展其JVM,恐怕此功能将无法使用。
There is no real possibility to make [mocking final classes] work in Android at the moment as it lacks the instrumentation API on top of which we are operating. The Android VM is not a standard VM and only implements a subset of the Java specification. As long as Google does not choose to extend its JVM, I am afraid that this feature will not work.
有一些选项可以根据您的用例更换它。
There are some options to replace it depending on your use case.
选项1:使用包装器
如果您想模拟 final
像 BluetoothDevice
这样的Android系统类,您可以简单地围绕该类创建一个非最终包装并使用 BluetoothDeviceWrapper
而不是 BluetoothDevice
:
If you wish to mock a final
Android system class like BluetoothDevice
you can simply create a non-final wrapper around that class and consume the BluetoothDeviceWrapper
in your code instead of the BluetoothDevice
:
class BluetoothDeviceWrapper {
private final BluetoothDevice bluetoothDevice;
BluetoothDeviceWrapper(BluetoothDevice bluetoothDevice) {
this.bluetoothDevice = bluetoothDevice;
}
public String getName() {
return bluetoothDevice.getName();
}
}
专业提示:您可以使用Android Studio的生成/委托
方法,通过按 Alt-Ins 或为您生成诸如 getName()
之类的委托方法 Cmd-N 并选择正确的选项。有关更详细的示例,请参见此答案。
Pro tip: you can use Android Studio's Generate / Delegate
methods to generate delegate methods like getName()
for you by pressing Alt-Ins or Cmd-N and choosing the correct option. See this answer for a more detailed example.
选项2:使用Robolectric之类的测试框架
Robolectric 提供Android类(如 Context
和 SQLiteDatabase
)的工作测试双倍测试(称为阴影)。您也许可以在开箱即用的测试中找到要尝试模拟的类的影子。
Robolectric provides working test doubles (called shadows) of Android classes like Context
and SQLiteDatabase
. You may be able to find a shadow of the class you are trying to mock in your test out of the box.
选项3:使用DexOpener
您也可以尝试使用库 DexOpener 并能够在Android中模拟最终课程。
You can also try the library DexOpener with the ability to mock final classes in Android.
这篇关于如何使用Mockito2在java / androidTest下模拟最终分类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!