1

I was unit testing a simple app today. I have a method

protected void onRestart() {
    disp.setText("The numbers you entered were");
    super.onRestart();
}

And in my test case i'm using

public void testRestart(){
    String dispText = disp.getText().toString();
    getInstrumentation().callActivityOnStop(mActivity);
    assertEquals(dispText, disp.getText().toString());
}

The assertion returns true meaning that the text isn't changed. However when i use

public void testRestart(){
    String dispText = disp.getText().toString();
    getInstrumentation().callActivityOnRestart(mActivity);
    assertEquals(dispText, disp.getText().toString());
}

the assertion is false as expected.

According to the activity lifecycle onRestart() should always be called after onStop() if the user navigates away from the activity.

Shouldn't the onRestart() method be called after onStop() ? Or does calling getInstrumentation().callActivityOnStop(mActivity); kill the activity, instead of just stopping it ?

Traxex1909
  • 2,650
  • 4
  • 20
  • 25

1 Answers1

3

ActivityUnitTestCase is an isolated, unit test of a single Activity. The Activity Under Test does not participate of the system interactions.

You can start your Activity using startActivity(), and it will invoke onCreate(), however if you wish to further exercise Activity life cycle methods, you must call them yourself from your test case.

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
  • Ya i get that. My question is that are the lifecycle methods completely independent of each other ? Shouldn't calling `callActivityOnStop` call onStop() and then onRestart() ? Or does it just call onStop() only ? – Traxex1909 Aug 09 '13 at 05:33
  • In the case you mentioned, you must call lifecycle methods, so calling `onStop()` won't call `onRestart()` – Diego Torres Milano Aug 09 '13 at 06:37