java - 在 Espresso Java/Android 中等待匹配器

标签 java android unit-testing junit android-espresso

我从 here 中找到了一个非常酷的代码块这有助于执行等待功能,直到资源 withId(int) 出现 - 当我实际上有一个资源 ID 可以使用时,它似乎工作正常。

但是,我正在使用的应用程序通常没有简单的资源 ID,我必须改为使用 Matchers。

一个例子:

Matcher secondBanner = allOf(childAtPosition(allOf(withId(R.id.story_details_body),
                childAtPosition(IsInstanceOf.<View>instanceOf(
                android.widget.LinearLayout.class),2)),0)))

有什么方法可以像资源 ID 一样在 Matcher 上执行类似的等待?

我在上一个链接中指的代码是 -

/** Perform action of waiting for a specific view id. */
public static ViewAction waitId(final int viewId, final long millis) {
  return new ViewAction() {
    @Override
    public Matcher<View> getConstraints() {
        return isRoot();
    }

    @Override
    public String getDescription() {
        return "wait for a specific view with id <" + viewId + "> during " + millis + " millis.";
    }

    @Override
    public void perform(final UiController uiController, final View view) {
        uiController.loopMainThreadUntilIdle();
        final long startTime = System.currentTimeMillis();
        final long endTime = startTime + millis;
        final Matcher<View> viewMatcher = withId(viewId);

        do {
            for (View child : TreeIterables.breadthFirstViewTraversal(view)) {
                // found view with required ID
                if (viewMatcher.matches(child)) {
                    return;
                }
            }

            uiController.loopMainThreadForAtLeast(50);
        }
        while (System.currentTimeMillis() < endTime);

        // timeout happens
        throw new PerformException.Builder()
                .withActionDescription(this.getDescription())
                .withViewDescription(HumanReadables.describe(view))
                .withCause(new TimeoutException())
                .build();
    }
};
}

我尝试简单地将所有内容从 withId(int) 更改为 Matcher 但无济于事。

那么是否可以将这段代码转换成可以执行等待/超时的代码?

感谢您提供的所有帮助。

最佳答案

您可以简单地使用 Thread.sleep(timeInMilisec)。它会按原样等待某个指定的时间。

Idling Resources没关系,但您不仅需要在测试中添加一些额外的代码,还需要在您的项目中添加一些额外的代码。您可以在代码中指定测试何时应该等待以及何时应该再次进行。

关于java - 在 Espresso Java/Android 中等待匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42865182/

相关文章:

Java Play 框架隐藏 URL 路由

java - 一对一单向 hibernate 映射在创建表时不创建外键

java - 无法使用Gradle输出jar文件

android - keytool 和 openssl 证书指纹不匹配

c# - 单元测试错误 : This function can only be invoked from LINQ to Entities

java - 使用 Guava Ordering 对对象列表进行多标准排序

android - Nestedscrollview 内的 Webview 内容滚动不顺畅

unit-testing - 在未安装 Visual Studio 的情况下使用 vstest.console.exe 运行 c++ unittest

java - 如何模拟 getApplicationContext

java - 使用来自依赖 jar 的 Spring CacheManager