【问题标题】:How to get context in uiautomator test case?如何在 uiautomator 测试用例中获取上下文?
【发布时间】:2013-09-12 06:12:28
【问题描述】:

我有我的 uiautomator 测试用例:

public class clickTest extends UiAutomatorTestCase {   

   public void myTest() throws UiObjectNotFoundException {   
       ...
       //Is it possible to get Context or Activity here?  

   }
}

我想知道,是否有可能在 UiAutomatorTestCase 中获得 ContextActivity 实例?

或者如何在UiAutomatorTestCase 中获取PackageManager

【问题讨论】:

  • 您当然无法访问Activity,因为它在单独的进程中运行。我不知道你也可以得到Context,更不用说PackageManager了。
  • 谢谢,我也是这么想的,我发布这个问题只是为了确保:),我想访问上下文的原因是我想在我的测试中使用 PackageManager。让我们看看他们的其他人是否对此了解更多
  • 你会声明并实例化clickText吗?

标签: android performance android-intent android-uiautomator


【解决方案1】:

2021 年,这就是答案:

为正在检测的目标应用程序获取上下文。 See details here: InstrumentationRegistry.getInstrumentation().getTargetContext();

获取仪器包的上下文。 See details here: InstrumentationRegistry.getInstrumentation().getContext();

【讨论】:

    【解决方案2】:

    您可以通过直接从您的 uiautomator 测试用例运行命令来使用 PackageManager:

    Runtime.getRuntime().exec("pm uninstall com.example.MyApp");
    

    但是,如果您需要访问上下文、Activity 等,最好使用 Android 的 InstrumentationTestRunner,查看优秀的 Android 文档以获取更多信息。 http://developer.android.com/tools/testing/activity_test.html

    【讨论】:

      【解决方案3】:

      这可以通过 UiAutomator 2.0 或更高版本实现。

      UiAutomator 的原始版本作为 shell 程序运行 (adb shell uiautomator runtest ...)。由于它不是作为 Android 应用程序运行的,因此它无权访问应用程序 Context 对象。

      UiAutomator 2.0 基于Android Instrumentation。测试被编译为 APK,并在应用程序进程中运行(通过adb shell am instrument ...)。如果您的测试扩展了InstrumentationTestCase,您可以使用getInstrumentation().getContext() 来获取上下文。

      有关详细信息,请参阅UiAutomator docs

      【讨论】:

        【解决方案4】:
        @RunWith(AndroidJUnit4.class)
        @SdkSuppress(minSdkVersion = 18)
        public class MyTest {
        
            @Test
            public void test1() {
        
                Context context = InstrumentationRegistry.getContext();
            }
        }
        

        【讨论】:

          【解决方案5】:

          这个有效 -

          InstrumentationRegistry.getInstrumentation().targetContext
          

          【讨论】:

            猜你喜欢
            • 2014-08-31
            • 2012-01-26
            • 1970-01-01
            • 2019-03-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多