I am writing an Android ApplicationTestCase (TemperatureConverterApplicationTests example found in Android Application Testing Guide by Diego T. Milano on page 171). The example was written for Android 2.3 and it doesn't seem to work for Android 4. You don't have to know the book to understand the problem as I have simplified it.
This works fine with Android 2.3.3 (API 10):
setContext(new MockContext());
createApplication();
[To be precise an UnsupportedOperationException is thrown because getPackageName() is not implemented. But this is normal and can be solved by using a subclass of MockContext() that implements getPackageName() and getSharedPreferences(). This is not relevant because the problem still exists even after doing this.]
The problem is that with Android 4.1.2 (API 16) it does not work. I get an AssertionFailedError that through some debugging I found out to be due to an ClassCastException being thrown on line 100 of ApplicationTestCase.
mApplication = (T) Instrumentation.newApplication(mApplicationClass, getContext());
The ClassCastException message is:
java.lang.ClassCastException: android.test.mock.MockContext cannot be cast to android.app.ContextImpl
Any suggestions why this happens and how it can be avoided?
EDIT: Related question: Android ApplicationTestCase using a MockContext