Unit Test Android : starting an activity

In this article, we will cover how to test « starting an Activity ».
As you should know – if you are an android developer – you can start an activity by either calling startActivity(Intent) or
startActivityForResult(Intent, int). The first method belongs to the Context objet while the latest belongs to the Activity object.
As testing environment, we will use Robolectric with Mockito.

For the sake of this study, we will create an ActivityLauncherController that has 2 methods to launch an Activity.

 

We rely on the Android framework, so the idea here is not testing that the NextActivity instances is effectively created when
calling startActivity(), but rather testing that the ActivityLauncherController has properly called the android API that will start
that Activity.

 

As you can see, to test the collaboration with the Context object on the first test, we need to spy a real Context instance so we
can verify the proper startActivity() call on that context.

On the second test, as our startNextActivityForResult() method requires an Activity instance, we can build that instance thanks to Robolectric.buildActivity() and then verify methods call on it.

Conclusion

Starting an activity is very simple on android. Testing it is not that difficult as we are testing the collaboration with the
framework and not the effective creation of the activity.

Laisser un commentaire

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