getTargetContext()和getContext(在InstrumentationRegistry上)有什么区别? [英] What's the difference between getTargetContext() and getContext (on InstrumentationRegistry)?

查看:1157
本文介绍了getTargetContext()和getContext(在InstrumentationRegistry上)有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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(),返回此内容的上下文 工具包.
  • InstrumentationRegistry.getTargetContext(), 返回目标应用程序的应用程序上下文.
  • InstrumentationRegistry.getArguments(),返回参数的副本 捆绑包已传递给此工具.这在以下情况下很有用 您要访问传递给的命令行参数 用于测试的仪器.
  • 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:

  1. 测试应用程序,它执行您的测试逻辑并测试您的真实"应用程序
  2. 真实"应用(您的用户将会看到)

因此,当您编写测试并想要加载真实应用程序的资源 时,请使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆