开发者

Android: how to get Context when testing with ActivityInstrumentationTestCase2?

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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜