Search code examples
androidunit-testingfunctional-testing

UnitTesting and Functional Testing on Android


I have created an app that sends intents among multiple activities. After doing some research I have found that the ActivityUnitTestCase class is designed for unit testing while the ActivityInstrumentationTestCase2 is designed for functional testing. I understand the use of methods such as setUp(), tearDown(), and testPreConditions(). However I am having a little difficulty in trying to figure out what user-defined-tests to create in the previously mentioned classes. I know that there are a few methods that cannot be called in certain classes.

To be more specific, if I am in activity A and I click a button then it calls startActivityForResult() which starts activity B. I then send an intent back to activity A which is handled in the onActivityResult() method. How can i test that the actual result in onActivityResult() is equal to the expected result?

I have been looking extensively for any kind of examples that would help clear up this confusion. If anyone could provide any assistance i would greatly appreciate it.


Solution

  • For this type of thing, you would probably test the results sent to onActivityResult indirectly, by actually testing the changes made to the view by the view controller. We use an instance of ActivityInstrumentationTestCase2 coupled with the Robotium library (which I can highly recommend).

    public class AdvancedSearchActivityTest extends ActivityInstrumentationTestCase2<AdvancedSearchActivity> {
    
        private Solo solo;
    
        @Override
        protected void setUp() throws Exception {
            super.setUp();
            solo = new Solo(getInstrumentation(), getActivity());
        }
    
        public void testWhenActivityLoads_shouldShowCorrectWidgets() throws Exception {
            assertTrue(solo.searchText("Location:"));
            assertTrue(solo.searchText("Map Radius:"));
            assertTrue(solo.searchButton("Search"));
        }
    }
    

    The ActivityInstrumentationTestCase2 only specifies the base activity to start, so there's no reason you can't start other activities through the test (simulate a button click, etc) and then come back from those with the results. We've done that here many times. I'd avoid trying to have an integration-type test actually try to get the results from onActivityResult directly though.