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:
- The test app, that executes your test logic and tests your “real” app
- The “real” app (that your users will see)
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()
.