Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ActivityMonitor failure causes getActivity() never returns

I have a test case that uses Instrumentation.ActivityMonitor to check if an Intent was sent. This works fine when the test succeeds. If the assertion fails, the next test case hangs on the getActivity() call in setUp().

Am I supposed to make a call some method to clean up?

It appears to revolve around an Activity launching, but the ActivityMonitor not catching it. That is, the IntentFilter wasn't triggered. The test fails but the new Activity is never dismisses and seems to interfere with the next getActivity() call.

This problem is similar to another question, but this solution there (calling super.tearDown()) did not fix my problem.

public class SimpleActivityTest
    extends ActivityInstrumentationTestCase2<SimpleActivity> {

    private SimpleActivity activity;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        this.getInstrumentation().setInTouchMode(false);

        Intent intent = new Intent();
        intent.putExtra("DATA_ITEM_1", 1);
        intent.putExtra("DATA_ITEM_2", 2);
        this.setActivityIntent(intent);

        this.activity = getActivity(); // this call hangs on second test
    }

    public void testOtherActivityCalled() {
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_VIEW);
        ifilter.addDataScheme("http");
        ifilter.addDataAuthority("some.domain.com", null);
        ifilter.addDataPath("foobar", PatternMatcher.PATTERN_PREFIX);

        ActivityMonitor activityMonitor = getInstrumentation().addMonitor(
                ifilter, null, false);

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // launch other activity somehow
            }
        });
        getInstrumentation().waitForIdleSync();

        Activity otherActivity = activityMonitor.waitForActivityWithTimeout(2000);
        assertNotNull(otherActivity);
        otherActivity.finish();
    }

    public void testSomethingElse() {
        // This code will never run because getActivity() in setUp() will
        // never return
    }
}
like image 909
Cristian Avatar asked Feb 03 '12 00:02

Cristian


1 Answers

I suspect that the Runnable you've created is never exiting. Since it's running on the UI thread it never allows the Activity lifecycle to do what it needs. Is there any particular reason you're doing that from the UI thread?

like image 180
Brian Dupuis Avatar answered Oct 20 '22 10:10

Brian Dupuis