How to mock Final Clases under java/androidTest us

2019-06-21 05:36发布

enter image description hereFinal classes can be mocked under java/test when I define in gradle:

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

How to mock final classes under java/androidTest? This solution does not work:

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

Do you have any ideas?

3条回答
Viruses.
2楼-- · 2019-06-21 06:16

Mocking final classes is not supported for mockito-android as per this GitHub issue.

From one of the library maintainers:

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.

Option 1: Use wrappers

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();
   }
}

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.

Option 2: use a testing framework like Robolectric

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.

Option 3: use DexOpener

You can also try the library DexOpener with the ability to mock final classes in Android.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-06-21 06:31

You may now use dexmaker-mockito-inline. See here for details regarding variants of Mockito and their capabilities.

查看更多
三岁会撩人
4楼-- · 2019-06-21 06:36

I just got a response that the final mock maker does not work on Android.

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

查看更多
登录 后发表回答