What's the difference between getTargetContext() and getContext (on InstrumentationRegistry)?

Zsolt Safrany picture Zsolt Safrany · Apr 30, 2015 · Viewed 15.1k times · Source

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()?

Answer

Zsolt Safrany picture Zsolt Safrany · Apr 30, 2015

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:

  1. The test app, that executes your test logic and tests your "real" app
  2. 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().