Reputation: 273
I try to write an instrumentation test that tests the activity lifecycle where my activity gets killed and it's instance state gets saved and then gets recreated with this instance state.
I can test this behavior manually by limiting the background process limit to "no background processes" in the developer settings of my device, but I want to be able to have an automated test that proves that my activity can be recreated.
My activity has a fragment with id R.id.content_frame.
So for I have this:
public class MainActivityInstrumentationTest extends ActivityInstrumentationTestCase2<MainActivity> {
public void testKillCreateLifeCycleWithProfileFragment() throws Throwable {
final Activity activity = getActivity();
navigateToProfile(activity);
Thread.sleep(5000);
runTestOnUiThread(new Runnable() {
@Override
public void run() {
activity.recreate();
}
});
getInstrumentation().waitForIdleSync();
Thread.sleep(5000);
assertProfileFragmentIsVisible((FragmentActivity) activity);
}
private void assertProfileFragmentIsVisible(FragmentActivity activity) {
FragmentManager supportFragmentManager = activity.getSupportFragmentManager();
Fragment currentFragment = supportFragmentManager.findFragmentById(R.id.content_frame);
assertEquals(ProfileFragment.class.getName(), currentFragment.getClass().getName());
}
}
activity.recreate goes through all the live cycle callback methods and ultimalty calls onCreate with the saved bundle but the fragmentManager in my assertProfileFragmentIsVisible
method does not contain any fragments.
Also I'm not sure whether to use activity.recreate is a right way to go. I tried many other ways like calling each life cycle method manually with getInstrumentation().callActivityOn...
but then ultimately found no way of creating the activity with the saved bundle..
Any ideas on how I can create such an instrumentation test would be appreciated!
Regards Frank
Upvotes: 0
Views: 676
Reputation: 273
Just in case anybody is interested in my final solution:
The problem was that I put the reference to the old activity to assertProfileFragmentIsVisible
. But activity.recreate() creates a new activity instance.
The problem remains how to get this reference.
I managed to obtain a reference to the new activity by using the ActivityMonitor
.
So my complete test now looks as follows:
public void testKillCreateLifeCycle() throws Throwable {
Instrumentation.ActivityMonitor mainActivityMonitor = new Instrumentation.ActivityMonitor(MainActivity.class.getName(), null, false);
getInstrumentation().addMonitor(mainActivityMonitor);
final Activity activity = getActivity();
mainActivityMonitor.waitForActivityWithTimeout(5000);
navigateToFragment(activity);
runTestOnUiThread(new Runnable() {
@Override
public void run() {
activity.recreate();
}
});
getInstrumentation().waitForIdleSync();
Activity newActivity = mainActivityMonitor.getLastActivity();
assertFragmentIsVisible((FragmentActivity) newActivity, getExpectedFragment());
}
Upvotes: 3