Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AssertionFailedError in ApplicationTestCase.createApplication() in newer Android versions when using MockContext

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

like image 453
Omar Kohl Avatar asked Jan 06 '13 13:01

Omar Kohl


1 Answers

I get this behaviour too. I've worked around it by extending ContextWrapper:

public class RenamingMockContext extends RenamingDelegatingContext
{
    private static final String PREFIX = "test.";

    public RenamingMockContext(Context context)
    {
        super(new ContextWrapper(context), PREFIX);
    }

    @Override
    public String getPackageName()
    {
        return PREFIX + super.getPackageName();
    }
}
like image 141
barry Avatar answered Oct 26 '22 23:10

barry