0

I am attempting to instrumentation test an Activity in isolation however I'm running into issues because part of the testing requires that I verify that the Activity under test launches another Activity via an Intent.

What I'm looking for is some way to intercept an Intent so that I can verify that the isolated Activity actually attempted to launch the next Activity but without the next Activity actually launching.

The issue I'm running into is that when the next Activity launches it crashes because I'm unable to mock a few critical things that it requires. It would be perfect if there was a way to intercept the Intent during testing so that the next Activity never launches.

Is what I'm looking for even possible?

neonDion
  • 2,278
  • 2
  • 20
  • 39

1 Answers1

0

Originally I tried to use Espresso's intended() and intending() methods in order to verify that Intents were being sent without actually starting an Activity (as described here: https://collectiveidea.com/blog/archives/2015/08/11/stub-your-android-intents

However I did not have luck making that work. What I eventually resorted to was using ActivityMonitor to do the job.

Here's an example:

private void registerActivityMonitorAndStartActivity(String name) {
    Instrumentation.ActivityMonitor am = new 
    Instrumentation.ActivityMonitor(name, null, true);
    InstrumentationRegistry.getInstrumentation().addMonitor(am);

    mActivityTestRule.launchActivity(new Intent());

    int count = 0;

 while(!InstrumentationRegistry.getInstrumentation().checkMonitorHit(am, 1) && count < 50000) {
    count++;
}
    Timber.d("Count = " + String.valueOf(count));
assertTrue(InstrumentationRegistry.getInstrumentation().checkMonitorHit(am, 1));
}

This basically has an activity monitor watch for an intent sent to an activity that you specify by name. A while loop runs until the activity monitor sees a hit and then breaks or breaks if a timeout is hit.

neonDion
  • 2,278
  • 2
  • 20
  • 39