开发者

Android: how to get Context when testing with ActivityInstrumentationTestCase2?

开发者 https://www.devze.com 2023-03-06 14:31 出处:网络
I\'m开发者_StackOverflow中文版 running a junit test in Android which extends ActivityInstrumentationTestCase2. I\'m using this on order to start up an activity.

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

精彩评论

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