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

前端 未结 2 2379
名媛妹妹
名媛妹妹 2021-02-20 15:46

I am writing an Android ApplicationTestCase (TemperatureConverterApplicationTests example found in Android Application Testing Guide by Diego T. Milano on page 171). Th

相关标签:
2条回答
  • 2021-02-20 16:24

    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.

    0 讨论(0)
  • 2021-02-20 16:27

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题