Espresso - 检查屏幕是否可见

3
我正在尝试使用新的Android测试套件(Espresso)编写一些测试。但我找不到任何有关如何检查视图是否显示并对其执行某些操作(例如点击按钮等)的信息。请注意,我需要检查视图是否存在。如果存在,则对该视图执行操作;如果不存在,则继续下一个视图。
任何帮助都将不胜感激。我只需要一个链接或一些基础示例代码:
检查视图是否存在 如果是,执行操作 如果不是,则继续到下一个屏幕。
3个回答

2
Object currentActivity;

@Nullable
private Activity getCurrentActivity() throws Throwable {
    getInstrumentation().waitForIdleSync();
    getInstrumentation().runOnMainSync(new Runnable() {
        public void run() {
            Collection resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(RESUMED);
            if (resumedActivities.iterator().hasNext()) {
                currentActivity = resumedActivities.iterator().next();
            }
        }
    });

    return (Activity) currentActivity;
}

使用此方法,您可以获取当前显示的Activity。然后,通过执行类似以下操作的方式,您可以创建一个安全代码段。

HOMESCREEN:
        {
            for (; ; ) {
                if (getCurrentActivity() != null) {
                    //check if it is the required screen
                    if (getCurrentActivity().getLocalClassName().toLowerCase().contains("homescreen")) {
                        //if it is the required screen, break the 
                        //loop and continue execution
                         break HOMESCREEN;
                    }  else {
                        //wait for 2 seconds and run the loop again
                        sleep(2000);
                    }
                } else {
                    break HOMESCREEN;
                }
            }
        }

sleep(2000)是一个自定义函数,仅仅调用了像下面展示的thread.sleep函数:

private void sleep(long milliseconds) {
    try {
        Thread.sleep(millis);
    } catch (InterruptedException e) {
        throw new RuntimeException("Cannot execute Thread.sleep()");
    }
}

2
您可以使用经典的"try/catch"选项:
try {
    onView(withText("Text")).check(matches(isDisplayed()));
    //perform some actions on this view
} catch (NoMatchingViewException notExist) {
    //proceed to the next screen
}

可以工作,尽管我不得不捕获Throwable而不是NoMatchingViewException(Espresso 3.4.0)。 - Myroslav

1

您必须控制测试的行为。因此,您必须添加一些前提条件,或创建@Rule来控制行为,例如通过添加参数来确定是否显示视图。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接