如何在uiautomator测试用例中获取上下文?

时间:2013-09-08 17:37:29

标签: android performance android-intent uiautomator android-uiautomator

我有我的uiautomator测试用例:

public class clickTest extends UiAutomatorTestCase {   

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

   }
}

我想知道,是否可以在Context中获得ActivityUiAutomatorTestCase个实例?

或如何在PackageManager中获取UiAutomatorTestCase

5 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

@RunWith(AndroidJUnit4.class)
@SdkSuppress(minSdkVersion = 18)
public class MyTest {

    @Test
    public void test1() {

        Context context = InstrumentationRegistry.getContext();
    }
}

答案 3 :(得分:0)

此作品有效-

InstrumentationRegistry.getInstrumentation().targetContext

答案 4 :(得分:0)

2021 年的答案是:

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

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

相关问题