I am using ActiveAndroid for some of my models, and I wanted to start unit testing my work. Unfortunately, I am getting a load of errors, namely in being unable to initialize ActiveAndroid using the proper context.
ActiveAndroid is iniatilized:
ActiveAndroid.initialize(context)
I have tried to initialize a context by:
Have a stub class that extends Application, and use that to initialize db.
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); } }
This fails, as the class return null for .getPackageName() and .getApplicationContext(), both of which are used internally by the initialize.
I have also tried using ShadowContextWrapper, but I may be using it wrong. Here is how I went about it:
ShadowContextWrapper shadowContextWrapper = new ShadowContextWrapper();
shadowContextWrapper.setApplicationName("appName");
shadowContextWrapper.setPackageName("package");
Context context = shadowContextWrapper.getApplicationContext();
This approach fails with an NPE at ShadowContextWrapper.java:52 which part of Robolectric. The line itself:
Context applicationContext = this.realContextWrapper.getBaseContext().getApplicationContext();
I am using AS 1.2, robolectric3.0 and activeandroid 3.1.
Here is an example of a Test I am running.
@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(){
}
}
My custom Runner is as follows:
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);
}
}