Final 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?
Mocking final classes is not supported for
mockito-android
as per this GitHub issue.From one of the library maintainers:
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 likeBluetoothDevice
you can simply create a non-final wrapper around that class and consume theBluetoothDeviceWrapper
in your code instead of theBluetoothDevice
:Pro tip: you can use Android Studio's
Generate / Delegate
methods to generate delegate methods likegetName()
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
andSQLiteDatabase
. 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.
You may now use
dexmaker-mockito-inline
. See here for details regarding variants of Mockito and their capabilities.I just got a response that the final mock maker does not work on Android.
https://github.com/mockito/mockito/issues/1173#issuecomment-324401986