我正在为我的一些模型使用 ActiveAndroid,我想开始对我的工作进行单元测试。不幸的是,我遇到了很多错误,即无法使用正确的上下文初始化 ActiveAndroid。
ActiveAndroid 初始化:
ActiveAndroid.initialize(上下文)
我试图通过以下方式初始化上下文:
有一个扩展应用程序的存根类,并使用它来初始化数据库。
private class TestApp extends com.activeandroid.app.Application{ @Override public void onCreate() { super.onCreate(); initialiseDB(getDatabaseName()); } protected String getDatabaseName() { return "sad"; } private void initialiseDB(String dbName) { ActiveAndroid.initialize(this); } }
这失败了,因为类为 .getPackageName() 和 .getApplicationContext() 返回 null,这两者都由初始化在内部使用。
我也尝试过使用 ShadowContextWrapper,但我可能用错了。这是我的做法:
ShadowContextWrapper shadowContextWrapper = new ShadowContextWrapper();
shadowContextWrapper.setApplicationName("appName");
shadowContextWrapper.setPackageName("package");
Context context = shadowContextWrapper.getApplicationContext();
这种方法在 ShadowContextWrapper.java:52 上的 NPE 失败,该 NPE 是 Robolectric 的一部分。线路本身:
Context applicationContext = this.realContextWrapper.getBaseContext().getApplicationContext();
我正在使用 AS 1.2、robolectric3.0 和 activeandroid 3.1。
这是我正在运行的测试的示例。
@RunWith(CustomRobolectricTestRunner.class)
public class ItemTest {
public void setUp(){
}
@Test
public void checkJUnitWork() {
assertThat(true, is(true));
}
@Test
public void testSave(){
Item item = new Item("name", "units", 5.0, 4.5, 10.0);
assertThat(item.getName(),is("name"));
}
public void tearDown(){
}
}
我的自定义 Runner 如下:
public class CustomRobolectricTestRunner extends RobolectricTestRunner {
public CustomRobolectricTestRunner(Class<?> testClass)
throws InitializationError {
super(testClass);
String buildVariant = (BuildConfig.FLAVOR.isEmpty()
? "" : BuildConfig.FLAVOR+ "/") + BuildConfig.BUILD_TYPE;
String intermediatesPath = BuildConfig.class.getResource("")
.toString().replace("file:", "");
intermediatesPath = intermediatesPath
.substring(0, intermediatesPath.indexOf("/classes"));
System.setProperty("android.package",
BuildConfig.APPLICATION_ID);
System.setProperty("android.manifest",
intermediatesPath + "/manifests/full/"
+ buildVariant + "/AndroidManifest.xml");
System.setProperty("android.resources",
intermediatesPath + "/res/" + buildVariant);
System.setProperty("android.assets",
intermediatesPath + "/assets/" + buildVariant);
ShadowContextWrapper shadowContextWrapper = new ShadowContextWrapper();
shadowContextWrapper.setApplicationName("appName");
shadowContextWrapper.setPackageName("package");
Context context = shadowContextWrapper.getApplicationContext();
ActiveAndroid.initialize(context);
}
}