Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 725
Zsolt Safrany Avatar asked Apr 30 '15 13:04

Zsolt Safrany


People also ask

What is InstrumentationRegistry?

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!

What are instrumented tests?

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.


1 Answers

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

like image 147
Zsolt Safrany Avatar answered Oct 02 '22 08:10

Zsolt Safrany