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

2

10

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

Inequality answered 6/1, 2013 at 13:57 Comment(1)
I'm having the exact same problem. It works fine using a class that extends RenamingDelegatingContext but not a MockContext. I've posted a similar question here #14205951. I'll reply if I find anything.Haggle
L
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();
    }
}
Lusty answered 31/10, 2013 at 15:19 Comment(0)
U
0

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.

Undermanned answered 23/2, 2013 at 1:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.