Final classes can be mocked under java/test when I define in gradle:
testCompile "org.mockito:mockito-inline:+"
如何在java/androidTest下模拟最终类?该解决方案不起作用:
androidTestCompile“org.mockito:mockito-android:+”
你有什么想法?
不支持模拟最终课程mockito-android
as per 这个 GitHub 问题 https://github.com/mockito/mockito/issues/1173.
来自图书馆维护者之一:
目前还没有真正的可能让[模拟最终类]在Android中工作,因为它缺乏我们正在运行的仪器API。 Android VM 不是标准 VM,仅实现了 Java 规范的一个子集。只要Google不选择扩展其JVM,恐怕这个功能就无法发挥作用。
根据您的使用情况,有一些选项可以替换它。
选项 1:使用包装器
如果你想嘲笑final
Android系统类如BluetoothDevice
您可以简单地围绕该类创建一个非最终包装器并使用BluetoothDeviceWrapper
在你的代码中而不是BluetoothDevice
:
class BluetoothDeviceWrapper {
private final BluetoothDevice bluetoothDevice;
BluetoothDeviceWrapper(BluetoothDevice bluetoothDevice) {
this.bluetoothDevice = bluetoothDevice;
}
public String getName() {
return bluetoothDevice.getName();
}
}
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 https://stackoverflow.com/a/14292975/5241933 for a more detailed example.
选项 2:使用 Robolectric 等测试框架
机器人电动 http://robolectric.org/提供 Android 类的工作测试替身(称为影子),例如Context
and SQLiteDatabase
。您也许能够在开箱即用的测试中找到您尝试模拟的类的影子。
选项 3:使用 DexOpener
您也可以尝试图书馆德克斯开瓶器 https://github.com/tmurakami/dexopener能够在 Android 中模拟最终课程。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)