getTargetContext() 和 getContext(在 InstrumentationRegistry 上)有什么区别? [英] What's the difference between getTargetContext() and getContext (on InstrumentationRegistry)?
问题描述
我正在使用新的 Android 测试支持库 (com.android.support.test:runner:0.2
) 来运行仪器测试(又名设备或模拟器测试).
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).
我使用 @RunWith(AndroidJUnit4.class)
注释我的测试类并使用 Android Studio 运行它们.
I annotate my test class with @RunWith(AndroidJUnit4.class)
and use Android Studio to run them.
对于我的测试用例,我需要一个 Context
实例.我可以使用 InstrumentationRegistry
获得它,但它有两个与上下文相关的方法,目前尚不清楚有什么区别.
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.
InstrumentationRegistry.getContext()
和 InstrumentationRegistry.getTargetContext()
有什么区别?
推荐答案
InstrumentationRegistry
是一个公开的注册表保存对在其中运行的检测的引用的实例过程及其参数并允许注入以下内容实例:
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()
,返回当前正在运行的仪器.InstrumentationRegistry.getContext()
,返回这个的Context仪表包.InstrumentationRegistry.getTargetContext()
,返回目标应用程序的应用程序上下文.InstrumentationRegistry.getArguments()
,返回参数的副本传递给此 Instrumentation 的捆绑包.这在以下情况下很有用您想访问传递给的命令行参数用于测试的仪器.
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.
那么什么时候使用 getContext() 和 getTargetContext()?
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:
您知道,当您在 Android 上进行仪器测试时,您有两个应用程序:
You know that when you do instrumentation tests on Android then you have two apps:
- 测试应用,执行您的测试逻辑并测试您的真实"应用
- 真正的"应用(您的用户会看到)
因此,当您编写测试并希望加载真实应用的资源时,请使用 getTargetContext()
.
So when you are writing your tests and you want to load a resource of your real app, use getTargetContext()
.
如果您想使用测试应用的资源(例如,您的一个测试的测试输入),请调用 getContext()
.
If you want to use a resource of your test app (e.g. a test input for one of your tests) then call getContext()
.
这篇关于getTargetContext() 和 getContext(在 InstrumentationRegistry 上)有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!