Unit test Android : testing Fragment’s onSaveInstanceState

On a previous article, we saw how to retain some state of a custom Fragment when the latter is killed and recreated. Below a simple custom logical Fragment that saves a Parcelable into the state bundle and restore it.

The specificity of the test here will be to simulate an activity recreation (as the lifecycle of a Fragment is higly tight to the
Activity’s one) that has the CustomFragment as child.
As testing environment, we will use Robolectric with Mockito.

 

After having instanciated a CustomFragment as well as an Activity, we add that fragment to the activity.
There after, we modify the value of our parcelable (here a Point) that will be saved and restored through the Fragment lifecycle.
Then, we need to go through that life cycle, this is why we use the recreate() method of Activity that will create a new instance of that activity (note that this API is level 11, this is why we annotate our test with @TargetApi(11)), as well as a new instance of our Fragment.
So we get a reference of this new recreatedFragment and simply test that the initial customFragment is a different instance of the newly recreated one and of course, we test that the parcelable has the proper value (the one set before the saving).

Conclusion :

Instead of testing that the Parcelable is saved into the outState Bundle of the onSaveInstanceState() method and properly restored on the onCreateView() method, we simply verify that the Parcelable is correctly handled through the whole lifeCycle. This gives us the elegancy of ignoring where the savedInstanceState is restored (as there are various methods that could do that) and test that at a higher level.

2 réflexions au sujet de « Unit test Android : testing Fragment’s onSaveInstanceState »

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *