Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...