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.
1 2 3 4 5 6 7 8 9 10 11 12 |
public class ActivityLauncherController { public void startNextActivity(Context context) { Intent nextActivityIntent = new Intent(context, NextActivity.class); context.startActivity(nextActivityIntent); } public void startNextActivityForResult(Activity activity, int requestCode) { Intent nextActivityIntent = new Intent(activity, NextActivity.class); activity.startActivityForResult(nextActivityIntent , requestCode); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
@RunWith(RobolectricTestRunner.class) public class ActivityLauncherControllerTest { private Context context; private ActivityLauncherController activityLauncherController; @Before public void setUp() throws Exception { context = Robolectric.getShadowApplication().getApplicationContext(); activityLauncherController = new ActivityLauncherController(); } @Test public void shouldStartNextActivity() throws Exception { Context spyContext = spy(context); Intent expectedIntent = new Intent(spyContext, NextActivity.class); activityLauncherController.startNextActivity(spyContext); verify(spyContext).startActivity(expectedIntent); } @Test public void shouldStartNextActivityForResult() throws Exception { int requestCode = 1200; Activity activity = spy(Robolectric.buildActivity(Activity.class).create().start().visible().get()); Intent expectedIntent = new Intent(activity, NextActivity.class); activityLauncherController.startNextActivityForResult(activity, requestCode); verify(activity).startActivityForResult(expectedIntent, requestCode); } } |
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.