我正在尝试使用 UiAutomator 为 Android 应用程序(我有 apk 但没有源代码)编写 UI 自动化“黑盒”测试。 我在设置阶段无法打开抽屉应用程序。到目前为止我的代码是
@Override
public void setUp() throws Exception {
super.setUp();
mDevice = UiDevice.getInstance(getInstrumentation());
mDevice.pressHome();
//Wait for the app drawer icon to show up on the screen
mDevice.wait(Until.hasObject(By.desc("Apps")), 3000);
//Obtain reference to the app drawer button in order to click it
UiObject drawerIcon = mDevice.findObject(new UiSelector().description("Apps"));
drawerIcon.clickAndWaitForNewWindow();
//Finding and Clicking on the Sunshine app
UiObject drawer = mDevice.findObject(new UiSelector().resourceId("com.sec.android.app.launcher:id/apps_grid"));
UiObject appToTest = mDevice.findObject(new UiSelector().description("app-to-test-description"));
while (!appToTest.exists()) {
drawer.swipeLeft(3);
}
appToTest.clickAndWaitForNewWindow();
}
当我运行测试时,它应该打开应用程序(然后运行我尚未编写的各种测试方法。) 相反,它打开抽屉并挂起。我想有一种更好的方法来识别抽屉并滚动它直到找到正确的应用程序。 这是错误日志。
Running tests
Test running started
android.support.test.uiautomator.UiObjectNotFoundException: UiSelector[RESOURCE_ID=com.sec.android.app.launcher:id/apps_grid] at android.support.test.uiautomator.UiObject.getVisibleBounds(UiObject.java:891) at android.support.test.uiautomator.UiObject.swipeLeft(UiObject.java:315) at com.crisanti.roberto.uturistautomatedtest.UiAutomatorTest.setUp(UiAutomatorTest.java:29) at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191) at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176) at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555) at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1853)
最佳答案
如果您真的想从菜单中启动它,您已经回答了自己的问题。但是请记住,在不同的设备中,应用程序抽屉可能不同(三星和其他公司通常在 Android 的基础上自己做)。
作为替代,你可以
Context context = InstrumentationRegistry.getInstrumentation().getContext(); //gets the context based on the instrumentation
Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageNameOfYourApp); //sets the intent to start your app
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); //clear out any previous task, i.e., make sure it starts on the initial screen
context.startActivity(intent); //starts the app
您可以使用 UiAutomatorViewer 获得的包名称(在 sdk-folder/tools/中)。
如果你愿意,你可以等到应用真正启动时执行此操作(我假设你已经有一个 UiDevice 设备)。
device.wait(Until.hasObject(By.pkg(packageNameOfYourApp)), timeOut); //ofc you need to set timeout
这适用于任何设备/模拟器配置。
关于android - UiAutomator 选择应用程序以从应用程序抽屉中进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32024100/