Skip to content Skip to sidebar Skip to footer

Android Methods Are Not Mocked When Using Mockito

I'm writing a test which purpose is to test some methods in subclass of Adapter class (used by RecyclerView). To mock adapter behavior I've chosen Mockito library. Here's a simple

Solution 1:

Android support classes obey the same rules as the rest of Java regarding what can or can't be mocked; unfortunately, the method you're referring to (notifyDataSetChanged) is final. You may also consider this a hazard of mocking types you don't own, as the final semantics affect whether the class can be mocked.

Internally, Mockito works by creating a "subclass" (actually a proxy implementation) of the class you're mocking. Because final method resolution can happen at compile time, Java skips the polymorphic method lookup and directly invokes your method. This is slightly faster in production, but without the method lookup Mockito loses its only way to redirect your call.

This is a common occurrence across the Android SDK (recently solved with a modified version of android.jar which has the final modifiers stripped off) and support libraries. You might consider one of the following resolutions:

  1. Refactor your system to introduce a wrapper class that you control, which is simple enough to require little or no testing.

  2. Use Robolectric, which uses a special Android-SDK-targeted JVM classloader that can rewrite calls into mockable equivalents (and also parses and supplies Android resources for testing without an emulator). Robolectric provides enough Android-specific "shadows" (replacement implementations) that you can usually avoid writing your own, but also allows for custom shadows for cases like support libraries.

  3. Use PowerMock, which extends Mockito or EasyMock using a special classloader that also rewrites the bytecode of your system under test. Unlike Robolectric, it is not Android-targeted, making it a more general-purpose solution but generally requiring more setup.

    PowerMock is an extension of Mockito, so it provides strictly more functionality, but personally I try to refactor around any problem that would require it.

Post a Comment for "Android Methods Are Not Mocked When Using Mockito"