gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:52:23 26 4
gpt4 key购买 nike

我正在使用新的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com