I'm开发者_StackOverflow中文版 running a junit test in Android which extends ActivityInstrumentationTestCase2. I'm using this on order to start up an activity.
The activity uses a subclass of the application object to obtain some parameters. I get the application object from the context.
Unfortunately, ActivityInstrumentationTestCase2 does not provide access to the context. Is there a way to access the context before getting the activity?
You can get the application context from the instrumentation object:
getInstrumentation().getTargetContext().getApplicationContext()
To be able to inject an Application using setApplication() you should use ActivityUnitTestCase, as it is only available in this test case class.
By default, ActivityUnitTestCase, creates a hidden MockApplication object that is used as the application under test.
For those using
AndroidTestCase
and needing the app application subclass:
MyApplication context = (MyApplication) getContext().getApplicationContext();
精彩评论