如何使用Mockito2在java / androidTest下模拟Final Clases?

时间:2017-08-23 15:09:39

标签: android class testing mockito final

enter image description here当我在gradle中定义时,可以在java / test下模拟最终类:

  

testCompile" org.mockito:mockito-inline:+"

如何在java / androidTest下模拟final类?此解决方案不起作用:

  

androidTestCompile" org.mockito:mockito-android:+"

你有什么想法吗?

4 个答案:

答案 0 :(得分:7)

根据this GitHub issuemockito-android不支持模拟最终课程。

来自其中一位图书馆维护者:

  

由于缺少我们正在运行的检测API,因此目前没有可能让[模拟最终类]在Android中工作。 Android VM不是标准VM,只实现Java规范的子集。只要Google不选择扩展其JVM,我担心此功能将无效。

根据您的使用情况,有一些选项可以替换它。

选项1:使用包装

如果你想模拟像final这样的BluetoothDevice Android系统类,你可以简单地围绕该类创建一个非最终包装,并在代码中使用BluetoothDeviceWrapper而不是{ {1}}:

BluetoothDevice

专业提示:您可以使用Android Studio的class BluetoothDeviceWrapper { private final BluetoothDevice bluetoothDevice; BluetoothDeviceWrapper(BluetoothDevice bluetoothDevice) { this.bluetoothDevice = bluetoothDevice; } public String getName() { return bluetoothDevice.getName(); } } 方法为您生成委托方法,例如Generate / Delegate,方法是按 Alt-Ins Cmd-N 并选择正确的选项。有关更详细的示例,请参阅this answer

选项2:使用Robolectric等测试框架

Robolectric提供了类getName()Context等Android类的工作测试双打(称为阴影)。您可以在开箱即用的测试中找到您想要模拟的类的阴影。

选项3:使用DexOpener

您还可以尝试使用库DexOpener来模拟Android中的最终类。

答案 1 :(得分:1)

您现在可以使用dexmaker-mockito-inline。有关Mockito的变体及其功能的详细信息,请参见here

答案 2 :(得分:0)

我得到的回复是最终的模拟制作者无法在Android上运行。

https://github.com/mockito/mockito/issues/1173#issuecomment-324401986

答案 3 :(得分:0)

最后的类,对象,构造函数都可以用嘲笑来模仿 https://mockk.io/

相关问题