mfeingold
mfeingold

Reputation: 7154

Activity unit testing

I have an activity which preforms some work in the background and based on the result of this work starts one of two other activities. How can I write a unit test to validate its behavior?

I tried to use ActivityUnitTestCase but it blows up on an attempt to show a progress dialog. With ActivityInstrumentationTestCase2 I could not find any way to intercept activity destruction. Any word of advice?

Upvotes: 4

Views: 2348

Answers (1)

Diego Torres Milano
Diego Torres Milano

Reputation: 69208

ActivityInstrumentationTestCase2 is the correct approach as the other class is deprecated. To test what has happened after your main Activity, let's call it the ProgressActivity, you should use an ActivityMonitor. I think you want to intercept the Activity creation, not the destruction.

I'm assuming here that ProgressActivity starts another Activity (let's say A1, A2, or A3) after some calculation is done in the background.

Your test case should be something like this:

public static final HashSet<Class<? extends Activity>> TARGET_ACTIVITIES = new HashSet<Class<? extends Activity>>();
static {
    TARGET_ACTIVITIES.add(A1.class);
    TARGET_ACTIVITIES.add(A2.class);
    TARGET_ACTIVITIES.add(A3.class);
}

private static final int TIMEOUT = 7000;

public void testRandomActivityStarted() {
    @SuppressWarnings("unused")
    ProgressActivity activity = getActivity();
    final Instrumentation inst = getInstrumentation();
    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MAIN);
    intentFilter.addCategory("MY_CATEGORY");
    ActivityMonitor monitor = inst.addMonitor(intentFilter, null, false);
    // Wait, before the Activity started
    monitor.waitForActivityWithTimeout(TIMEOUT);
    assertEquals(1, monitor.getHits());
    Activity randomActivity = monitor.getLastActivity();
    Log.d(TAG, "monitor=" + monitor + "   activity=" + randomActivity);
    // Unfortunately, it seems randomActivity is always null even after a match
    if ( randomActivity != null ) {
        assertTrue(TARGET_ACTIVITIES.contains(randomActivity.getClass()));
    }
    inst.removeMonitor(monitor);
}

The trick here is to use a category in the IntentFilter, because if you rely on getLastActivity() you may be disappointed as it seems it's always null. To be able to match this category you should use it when you start A1, A2 or A3 (Intent.addCatrgory())

This example was adapted from the one that illustrates ActivityMonitor in Android Application Testing Guide.

Upvotes: 4

Related Questions