Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an activity from an AndroidTestCase

I am writing an android test case which requires the execution of a seperate Activity to the Activity being tested (not for the sake of testing but just to gain access to the contentresolver so I can change some telephony settings).

Is it at all possible to start an activity from a test case or in another manner.

I am aware of the AndroidTestCase class used to test activities, an I am using it in my tests, however I need to use a ContentResolver to change telephony settings and then test the reaction of the activity under test so I need another application component to change these settings.

Note: I release the complexity behind multiple activity testing (requiring an ActivityManager) but I only want to use it's method to alter the settings so I could even have the logic in the onCreate method.

like image 209
rogermushroom Avatar asked Jan 23 '26 08:01

rogermushroom


1 Answers

Android provides a special instrumentation framework for testing Activities. You must use this framework since Activities have a complex lifecycle that is un-invokable outside this provided framework. Look under the Testing link in the Developmentsection of the Android documentation for Activity Testing. If this doesn't answer your question, you might rephrase it a bit.

Edit

You should really be extending ActivityUnitTestCase to test an Activity, not AndroidTestCase. You get more functionality specific to what you need to test. If you extend ActivityUnitTestCase there is a function called launchActivity. It'll launch the activity you need and give you an instance of the activity so that you can call methods on it such as set, get, and finish. This should do anything you need for manipulating single and multiple activities at a time.

Example code:

@MediumTest
public class Test extends ActivityUniTestCase<HelloActivity> {

    public Test(Class<HelloActivity> activityClass) {
        super(activityClass);
    }

    @MediumTest
    public void testLifeCycleCreate() {
        HelloActivity hActivity = startActivity(new Intent(Intent.ACTION_MAIN), null, null);
        getInstrumentation().callActivityOnStart(hActivity);
        getInstrumentation().callActivityOnResume(hActivity);

        GoodByeActivity gActivity = launchActivity("package.goodbye", GoodByeActivity.class, null);
        gActivity.finish();
    }
}
like image 109
Spidy Avatar answered Jan 26 '26 00:01

Spidy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!