我是 Android 测试的新手,我正在尝试使用 MockContext 创建一个 ApplicationTestCase(实际上我正在尝试使用重命名模拟上下文)。但我不断收到 AssertionFailedError。到目前为止,这是我非常基本的代码:
AppTests.java
package com.myProject.test;
import android.test.ApplicationTestCase;
public class AppTests extends ApplicationTestCase<MyApplication> {
public AppTests() {
super(MyApplication.class);
}
@Override
protected void setUp() throws Exception {
final RenamingMockContext mockContext = new RenamingMockContext(getContext());
setContext(mockContext);
createApplication();
}
}
我的应用程序.java
package com.myProject.test;
import android.app.Application;
public class MyApplication extends Application {
public MyApplication() {
}
@Override
public void onCreate() {
super.onCreate();
}
}
重命名MockContext.java
package com.myProject.test;
import android.content.Context;
import android.content.SharedPreferences;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContext;
public class RenamingMockContext extends RenamingDelegatingContext {
private static final String PREFIX = "test.";
public RenamingMockContext(Context context) {
super (new DelegatedMockContext(context), PREFIX);
//super(context, PREFIX);
}
private static class DelegatedMockContext extends MockContext {
private Context mDelegatedContext;
public DelegatedMockContext(Context context) {
mDelegatedContext = context;
}
@Override
public String getPackageName() {
return mDelegatedContext.getPackageName();
}
@Override
public SharedPreferences getSharedPreferences(
String name, int mode) {
return mDelegatedContext.getSharedPreferences(
PREFIX + name, mode);
}
}
}
故障跟踪:
junit.framework.AssertionFailedError
at android.test.ApplicationTestCase.setupApplication(ApplicationTestCase.java:102)
at android.test.ApplicationTestCase.createApplication(ApplicationTestCase.java:118)
at com.myApplication.test.AppTests.setUp(AppTests.java:14)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1710)
请注意,如果我在被注释掉的 RenamingMockContext 构造函数中使用第二个 super() 调用(所以不要使用扩展的 MockContext 类),它可以正常工作。
这是从单元测试中调用 getSharedPreferences() 时的参考UnsupportedOperationException ,这对我不起作用,我还通读了 Android Application Testing Guide 一书,其中给出了一个与此完全相同的示例,但是当我下载源代码并直接运行它时它给出了同样的错误。