【问题标题】:AssertionFailedError in ApplicationTestCase.createApplication() in newer Android versions when using MockContext使用 MockContext 时,较新 Android 版本中 ApplicationTestCase.createApplication() 中的 AssertionFailedError
【发布时间】:2013-01-06 13:57:22
【问题描述】:

我正在编写一个 Android ApplicationTestCase(TemperatureConverterApplicationTests 示例可在 Diego T. Milano 第 171 页的 Android 应用程序测试指南 中找到)。该示例是为 Android 2.3 编写的,它似乎不适用于 Android 4。您不必知道这本书就可以理解问题,因为我已经对其进行了简化。

这适用于 Android 2.3.3 (API 10):

setContext(new MockContext());
createApplication();

[准确地说,抛出 UnsupportedOperationException 是因为 getPackageName() 没有实现。但这是正常的,可以通过使用实现 getPackageName() 和 getSharedPreferences() 的 MockContext() 子类来解决。这无关紧要,因为即使这样做了,问题仍然存在。]

问题在于 Android 4.1.2 (API 16) 无法正常工作。我得到一个 AssertionFailedError,通过一些调试我发现这是由于 ApplicationTestCase 的第 100 行抛出了 ClassCastException。

mApplication = (T) Instrumentation.newApplication(mApplicationClass, getContext());

ClassCastException 消息是:

java.lang.ClassCastException: android.test.mock.MockContext cannot be cast to android.app.ContextImpl

有什么建议为什么会发生这种情况以及如何避免?

编辑:相关问题:Android ApplicationTestCase using a MockContext

【问题讨论】:

  • 我遇到了完全相同的问题。使用扩展 RenamingDelegatingContext 但不是 MockContext 的类可以正常工作。我在这里stackoverflow.com/questions/14205451/… 发布了一个类似的问题。如果有什么发现我会回复的。

标签: android android-4.0-ice-cream-sandwich android-testing


【解决方案1】:

我也有这种行为。我通过扩展 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】:

    Instrumentation.newApplication() 方法将返回一个Application 对象。您正在尝试将其转换为 T 是什么。如果T 不是Application 的超类或子类,您将获得ClassCastException。在 Java 中,您只能将对象转换为该对象的超类或子类。如果不是,则将引发异常。

    举例:

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

    这将在第二行抛出一个ClassCastException,因为您试图将x(一个Integer 对象)转换为String。因为StringInteger 不是彼此的子类或超类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-02
      • 2017-04-17
      • 1970-01-01
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      相关资源
      最近更新 更多