Android: how to get context when testing with ActivityInstrumentationTestCase2?

I run a junit test on Android that extends ActivityInstrumentationTestCase2. I use this to get started.

This 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 started?

+4
source share
3 answers

To be able to inject an application using setApplication () , you must use ActivityUnitTestCase , since it is available only in this test case class.

By default, an ActivityUnitTestCase creates a hidden MockApplication object that is used as a test application.

+3
source

You can get the application context from the toolbox object:

getInstrumentation().getTargetContext().getApplicationContext() 
+12
source

For those who use

 AndroidTestCase 

and you need a subclass of the application:

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

All Articles