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

use*_*503 6 testing android final class mockito

在此输入图像描述我在gradle中定义时,可以在java/test下模拟最终类:

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

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

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

你有什么想法?

Dav*_*son 8

mockito-android根据此GitHub问题,不支持模拟最终类.

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

由于缺少我们正在运行的仪器API,因此目前没有可能让[模拟最终类]在Android中工作.Android VM不是标准VM,只实现Java规范的子集.只要谷歌不选择扩展其JVM,我恐怕这个功能不起作用.

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

选项1:使用包装器

如果你想模拟一个finalAndroid系统类,BluetoothDevice你可以简单地创建一个围绕该类的非最终包装,并使用BluetoothDeviceWrapper你的代码代替BluetoothDevice:

class BluetoothDeviceWrapper {

   private final BluetoothDevice bluetoothDevice;

   BluetoothDeviceWrapper(BluetoothDevice bluetoothDevice) {
       this.bluetoothDevice = bluetoothDevice;
   }

   public String getName() {
       return bluetoothDevice.getName();
   }
}
Run Code Online (Sandbox Code Playgroud)

专业提示:您可以使用Android Studio的Generate / Delegate方法getName()通过按Alt-InsCmd-N选择正确的选项来生成类似的委托方法 .有关更详细的示例,请参阅此答案.

选项2:使用像Robolectric这样的测试框架

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

选项3:使用DexOpener

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

  • Robolectric就是这里的答案. (2认同)