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 te开发者_开发百科st 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.
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();
}
}
AndroidTestCase and ActivityInstrumentationTestCase2 both provide methods to get Context
AndroidTestCase:
getContext();
ActivityInstrumentationTestCase2
getInstrumentation().getContext();
You can use these contexts to launch another activity, however the permissions is adopted from the application under test, so in my case with the contentresolver I only have the same permission to alter settings I do in the application under test.
In my case this is no good so I had to create a seperate application with it's own permissions and a background service I was then able to control by launching intents using the context.
精彩评论