I'm using the new Android Testing Support Library (com.android.support.test:runner:0.2
) to run Instrumentation Tests (a.k.a Device or Emulator Tests).
I annotate my test class with @RunWith(AndroidJUnit4.class)
and use Android Studio to run them.
For my test cases I need a Context
instance. I can get it with InstrumentationRegistry
but it has two context related methods and it's not clear what the difference is.
What is the difference between InstrumentationRegistry.getContext()
vs. InstrumentationRegistry.getTargetContext()
?
platform. app. InstrumentationRegistry#registerInstance(Instrumentation, Bundle) . Records/exposes the instrumentation currently running and stores a copy of the instrumentation arguments bundle in the registry. This is a global registry, so be aware of the impact of calling this method!
Note: Instrumented test, also known as instrumentation tests, are initialized in a special environment that gives them access to an instance of Instrumentation. This class provides access to the application context and APIs to manipulate the app under test and gives instrumented tests their name.
InstrumentationRegistry
is an exposed registry instance that holds a reference to the instrumentation running in the process and it's arguments and allows injection of the following instances:
InstrumentationRegistry.getInstrumentation()
, returns the Instrumentation currently running.InstrumentationRegistry.getContext()
, returns the Context of this Instrumentation’s package.InstrumentationRegistry.getTargetContext()
, returns the application Context of the target application.InstrumentationRegistry.getArguments()
, returns a copy of arguments Bundle that was passed to this Instrumentation. This is useful when you want to access the command line arguments passed to Instrumentation for your test.
EDIT:
So when to use getContext() vs getTargetContext()?
The documentation doesn't do a great job of explaining the differences so here it is from my POV:
You know that when you do instrumentation tests on Android then you have two apps:
So when you are writing your tests and you want to load a resource of your real app, use getTargetContext()
.
If you want to use a resource of your test app (e.g. a test input for one of your tests) then call getContext()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With