Search code examples
androidinstrumentationlauncherrobotium

Android Instrumentation Testing how to tell if current Activity is Home (Launcher) Screen?


I am trying to test drive an application feature using Robotium. One of the features is that when my initial activity is launched from a view on top of the activity stack it should clear the top of the stack and reuse the existing Activity i.g.("MainActivity").

Flow:

FirstScreen -> LoginActivityScreen -> RegistrationScreen -> FirstScreen

The solution is simple enough:

   Intent intent = new Intent(getBaseContext(), FirstScreen.class);
   intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
   startActivity(intent);

By setting the flag Intent.FLAG_ACTIVITY_CLEAR_TOP puts FirstScreen back on the top of my application stack.

The Test I am trying to write is to confirm that when the Hardware Back Button is pressed then the app is gone and the native Home(Launcher) application is the current Activity.

My Instrumentation TestCase:

    @Smoke
    public void testshouldBeOnLauncherHomeScreen() {
        // Monitor the Home (Launcher) Activity being Launched
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.MAIN");
        filter.addCategory("android.intent.category.HOME");
        ActivityMonitor monitor = getInstrumentation().addMonitor(filter, null, false);

        // go back to the launcher home
        robotium.goBack();

        assertEquals(1, monitor.getHits());
    }

I would prefer to assert that the activity of the Launcher app is the current activity. Any ideas or suggestions would be much appreciated.


Solution

  • I have was able to solve this using ActivityUnitTestCase rather than InstrumentationTestCase2. I trust the android OS to bring my FirstScreen to the top by adding the flag. Validating that the flag is set when issuing the intent to start my first screen is enough to give me confidence that my code is doing what I expect.

        Public void testThatStartedIntentHasClearTopFlag() {
            Activity activity startActivity(new Intent(), null, null);
            activity.findViewById(R.id.button).performClick();
            Intent intent = getStartedActivityIntent();
            assertEquals(Intent.FLAG_ACTIVITY_CLEAR_TOP, intent.getFlags());
        }