I try to use Robolectric to run tests for my Android application, which is using the android-support package. In my onCreate() method I call
getSupportLoaderManager().initLoader(0, null, this);
Unfortunately, getSupportLoaderManager() returns null here. Do I have to prepare anything to make the compatiblity classes available to robolectric?
I have the android.jar (android-8) and the android-support-v4.jar in the classpath in my test project, along with robolectric-1.2 snapshot version.
Test class:
@RunWith(RobolectricTestRunner.class)
public class HoebAppActivityTest {
@Test
public void shouldStartActivity() {
final MyActivity activity = new MyActivity();
System.out.println(activity.getSupportLoaderManager()); // return null
activity.onCreate(null);
}
}
Edit:
System.out.println(Robolectric.directlyOnFullStack(activity)
.getSupportLoaderManager());
outputs android.support.v4.app.LoaderManagerImpl@9a90b9 so I guess, I just need to feed this back to the activity? Seems like I am getting closer here.
Edit2: I tried to bind my own ShadowFragmentActivity:
@Implements(FragmentActivity.class)
public class ShadowFragmentActivity extends
com.xtremelabs.robolectric.shadows.ShadowFragmentActivity {
@RealObject
private FragmentActivity realActivity;
@Implementation
public LoaderManager getSupportLoaderManager() {
return Robolectric.directlyOnFullStack(realActivity)
.getSupportLoaderManager();
}
}
bound with
Robolectric.bindShadowClass(ShadowFragmentActivity.class);
This appears to work for the moment. I will have to try further to see if it does what I want. No idea if this is in any way the correct way to go or not.
Robolectric 1.x had poor support for the Android support library. Robolectric 2.0 is significantly better, and has full support for fragments. An alpha was just released today: