I must be missing something here. The JavaDoc of ActivityUnitTestCase
suggest that this test case tests an Activity in isolation from the system:
I'm doing tests with dagger, so probably this is your case too, since you probably want to just inject and do not call whatever is in Application.onCreate, so this one is works fine for me (api17+):
private Context mContext;
private Application mApplication;
@Override
protected void setUp() throws Exception {
super.setUp();
mContext = new ContextWrapper(getInstrumentation().getTargetContext()) {
@Override
public Context getApplicationContext() {
return mApplication;
}
};
mApplication = new MyAppMock();
mApplication.attachBaseContext(mContext);
setApplication(app);
}
public void testActivityCreated() {
Intent intent = AboutActivity.createIntent(mContext);
setActivityContext(mContext);
startActivity(intent, null, null);
assertNotNull(getActivity());
}
For < api16 you need to use reflection and call Application.attach(context)
instead Application.attachBaseContext()
to set Application.mLoadedApk
, otherwise it will crash.
I have put everything together and made demo app that shows how to test with dagger: https://github.com/vovkab/dagger-unit-test
It also shows how to mock your application, works for any android version.
Roboguice had the same issue. Check it here.