Jack BeNimble
Jack BeNimble

Reputation: 36723

Android: how to get Context when testing with ActivityInstrumentationTestCase2?

I'm 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?

Upvotes: 4

Views: 5394

Answers (3)

jayeffkay
jayeffkay

Reputation: 1299

For those using

AndroidTestCase

and needing the app application subclass:

MyApplication context = (MyApplication) getContext().getApplicationContext();

Upvotes: 0

Marco RS
Marco RS

Reputation: 8255

You can get the application context from the instrumentation object:

getInstrumentation().getTargetContext().getApplicationContext()

Upvotes: 14

Diego Torres Milano
Diego Torres Milano

Reputation: 69396

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.

Upvotes: 3

Related Questions