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

穿精又带淫゛_ 提交于 2019-12-05 17:26:58

问题


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


回答1:


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



回答2:


The Instrumentation.newApplication() method will return an Application object. You are trying to cast it to whatever T is. If T is not a super class or sub class of Application you will get a ClassCastException. In Java you can only cast an object to something that is a super class or sub class of that object. If it isn't then the exception will be thrown.

FOR EXAMPLE:

Object x = new Integer(0);
System.out.println((String)x);

This will throw a ClassCastException on the second line because your trying to cast x (an Integer object) to a String. Because a String and Integer are not sub or super classes of each other.



来源:https://stackoverflow.com/questions/14182822/assertionfailederror-in-applicationtestcase-createapplication-in-newer-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!