android - getTargetContext() 和 getContext(在 InstrumentationRegistry 上)有什么区别?

标签 android android-testing

我正在使用新的 Android 测试支持库 (com.android.support.test:runner:0.2) 来运行 Instrumentation Tests (又名设备或仿真器测试)。

我用 @RunWith(AndroidJUnit4.class) 注释我的测试类并使用 Android Studio 运行它们。

对于我的测试用例,我需要一个 Context 实例。我可以使用 InstrumentationRegistry 获得它,但它有两个与上下文相关的方法,不清楚有什么区别。

InstrumentationRegistry.getContext()InstrumentationRegistry.getTargetContext() 有什么区别?

最佳答案

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.

编辑:

So when to use getContext() vs getTargetContext()?

文档没有很好地解释差异,所以这里来 self 的 POV:

您知道,当您在 Android 上进行仪器测试时,您有两个应用程序:

  1. 测试应用,执行您的测试逻辑并测试您的“真实”应用
  2. “真正的”应用(您的用户将会看到)

因此,当您编写测试并希望加载真实应用程序的资源 时,请使用 getTargetContext()

如果您想使用您的测试应用的资源(例如,您的一项测试的测试输入)然后调用 getContext()

关于android - getTargetContext() 和 getContext(在 InstrumentationRegistry 上)有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29969545/

相关文章:

mockito - AndroidViewModel 和单元测试

android - RTSP 直播是否在 Android 1.5/1.6 上不起作用?

Android 低功耗蓝牙 (BLE) API 尚未准备好迎接黄金时段

android - 如何从 AsyncTask 获取列表项到主要 Activity ?

android - 在 Android Studio 中创建单独的测试模块/项目

android - 如何在 android studio 中运行 JUnit 测试?

ui-automation - 用于测试的 Webview 元素检查

Android alpha 测试 "Item not found"

android - NullPointer 异常将 Intent 字符串保存为实例状态 Android

android - 由于不同的应用程序签名,重新安装失败