问题描述
我写一个Android ApplicationTestCase(在发现TemperatureConverterApplicationTests例如 Android应用程序测试指南的迭戈T.米兰171页)。这个例子是为Android 2.3编写,它似乎并没有工作为Android 4.你不必知道这本书来了解这个问题,因为我已经简化了。
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.
这工作正常的的Android 2.3.3 (API 10):
This works fine with Android 2.3.3 (API 10):
setContext(new MockContext());
createApplication();
[待precise一个UnsupportedOperationException被抛出,因为getPackageName()未实现。但是,这是正常的,可以通过使用MockContext(的一个子类来解决),它实现getPackageName()和getShared preferences()。这是不相关的,因为即使这样做后问题仍然存在。] 的
现在的问题是,随着的Android 4.1.2 (API 16),这是行不通的。我得到通过一些调试,我发现是由于一个ClassCastException异常被抛出ApplicationTestCase线100的AssertionFailedError异常。
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());
在 ClassCastException异常的消息是:
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?
编辑:相关问题:Android ApplicationTestCase使用MockContext
推荐答案
我得到这个行为太。我已经通过延长ContextWrapper围绕它的工作:
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();
}
}
这篇关于在使用MockContext AssertionFailedError异常的ApplicationTestCase.createApplication()在新的Android版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!