UiAutomator - UiDevice无法通过选择器找到对象(包名和资源ID)

问题描述 投票:0回答:3

我无法在androidTest中找到使用UiAutomator的元素(UiObject2)。我获取了UiDevice实例并尝试使用以下方法查找对象:

MY_UI_DEVICE.findObject(By.res(CURRENT_PACKAGE, id));

CURRENT_PACKAGE是我的应用程序MY_UI_DEVICE.getCurrentPackageName()的包。我也尝试过这个:

MY_UI_DEVICE.wait(Until.findObject(By.res(CURRENT_PACKAGE, id)), 10000);

我可以看到应用程序在右侧屏幕上等待10秒钟(期望的对象仍然存在),但是在超时后它无法找到它并且测试失败。它总是在模拟器(API 23)上失败,但在真实设备(API 25)上很少有效。

当我调试代码时,我可以看到手动我可以通过在getChild(index)上调用AccessibilityNodeInfo方法的序列来获取正确的元素,但在运行时它甚至仍然失败,即使应用程序正在等待我期望特定元素的右侧屏幕。

我正在玩不同的UiDevice的功能,但没有任何帮助,我没有想法,所以任何帮助将不胜感激。

android android-testing uiautomator android-uiautomator
3个回答
2
投票

我的测试有两个问题:

  1. 第一个问题是在静态块中获取/初始化UiDevice实例(作为util类中的静态字段)。我把它移到@Beforeand它帮助部分地解决了这个问题。
  2. 使用从UiDevice获得的包名搜索元素时发生了另一个问题。我在InstrumentationRegistry.getTargetContext().getPackageName();完成了用google samples取代包裹。

0
投票

确保您的Test方法抛出UiObjectNotFoundException。我也遇到了UiObject2这个问题,直到我开始强制错误抛出

@Test
public void clockTest() throws UiObjectNotFoundException, InterruptedException {
    mDevice.click(1146,37); //click on clock top right corner
    Thread.sleep(1500);//wait 1.5 seconds for screen to load
    mDevice.click(1138,135);//clicks in shell
    Thread.sleep(1500);//wait 1.5s for screen to load

    UiObject2 dTSettingsButton = mDevice.findObject(By.text("Date & Time Settings"));
    //assertNotNull(dTSettingsButton);//find and assert the settings button
    dTSettingsButton.clickAndWait(Until.newWindow(), LAUNCH_TIMEOUT);//clicks the settings button

    UiObject2 timeFormatButton = mDevice.findObject(By.text("Select Time Format"));
    assertNotNull(timeFormatButton);//find and assert timeformat button
    timeFormatButton.clickAndWait(Until.newWindow(), LAUNCH_TIMEOUT);//click timeformat button

    UiObject2 twelveHourButton = mDevice.findObject(By.res("com.REDACTED.settings:id/first_btn"));
    assertNotNull(twelveHourButton);//find and assert twelvehour button
    twelveHourButton.clickAndWait(Until.newWindow(), LAUNCH_TIMEOUT);//click twelvehour button
}

0
投票

尝试使用UiSelector方法。这对我来说比By选择器更好

© www.soinside.com 2019 - 2024. All rights reserved.