Reputation: 36673
I'm testing a destroy/restart sequence to make sure a counter retains its original value (before it was being incorrectly incremented on the restart). I put a fix in and it worked, when I test manually. But the unit test always passes, whether I include the fix or not. As you can see in the code below, I'm getting the counter value, then restarting, getting the counter value again and comparing them. What could be the problem?
public void testNumCorrectEqualAfterDestroy() {
mCorrect = (TextView) mActivity.findViewById(R.id.correct);
int before = Integer.parseInt(mCorrect.getText().toString());
mActivity.finish();
mActivity = this.getActivity();
mCorrect = (TextView) mActivity.findViewById(R.id.correct);
int after = Integer.parseInt(mCorrect.getText().toString());
Assert.assertEquals(before, after);
}
Upvotes: 0
Views: 896
Reputation: 1703
ActivityInstrumentationTestCase2.getActivity()
starts the Activity the first time you call it, and then it simply returns that Activity in each subsequent call in the test case. Thus, you are still looking at the Activity that you finished.
After you finish the first Activity, you need to start a new one from the test. You can use InstrumentationTestCase.launchActivity()
, for example.
As another example, I've written a test that pushes a button in ActivityA that launches ActivityB for-result; the test then immediately kills ActivityA (via an orientation change, but finish() would work, too), and then the test gets a handle to the new ActivityA that the system creates when ActivityB is done and sends its result. The trick there was to have the test add an Instrumentation.ActivityMonitor and then have that monitor wait for the system to start the new ActivityA and give the test a handle to it.
Upvotes: 0
Reputation: 30168
I think finish() will not cycle your activity through the "appropriate" states. The way I've tested this lifecycle case before is like so:
...
//TODO: do not use getActivity, instead use the startActivity() method
//and pass a value in the Bundle parameter
...
getInstrumentation().callActivityOnStart(mActivity);
getInstrumentation().callActivityOnResume(mActivity);
//TODO: asssert that the value is the expected one (based on what you fed in the bundle)
Bundle newBundle = new Bundle();
getInstrumentation().callActivityOnSaveInstanceState(mActivity, newBundle);
getInstrumentation().callActivityOnPause(mActivity);
getInstrumentation().callActivityOnStop(mActivity);
getInstrumentation().callActivityOnDestroy(mActivity);
//initialize activity with the saved bundle
getInstrumentation().callActivityOnCreate(mActivity, newBundle);
getInstrumentation().callActivityOnResume(mActivity);
//TODO: assert that the value is the expected one
Upvotes: 1