Espresso检查视图要么不显示,要么不显示

时间:2016-12-23 08:04:39

标签: android android-espresso hamcrest

以下语句不起作用,因为doesNotExist()返回ViewAssertion而不是匹配器。没有try-catch的任何方式让它工作?

.check(either(matches(doesNotExist())).or(matches(not(isDisplayed()))));

3 个答案:

答案 0 :(得分:4)

我遇到了同样的问题,我的一个观点最初没有某个视图,但可以添加它并稍后隐藏它。 UI处于哪种状态取决于其他背景活动被破坏。

我最后只是编写了一个关于doesNotExist实现的变体:

public class ViewAssertions {
    public static ViewAssertion doesNotExistOrGone() {
        return new ViewAssertion() {
            @Override
            public void check(View view, NoMatchingViewException noView) {
                if (view != null && view.getVisibility() != View.GONE) {
                    assertThat("View is present in the hierarchy and not GONE: "
                               + HumanReadables.describe(view), true, is(false));
                }
            }
        };
    }
}

答案 1 :(得分:0)

如果要检查层次结构中是否存在视图,请使用以下断言。

ViewInteraction.check(doesNotExist());

如果要检查层次结构中是否存在视图但未向用户显示,请使用以下断言。

ViewInteraction.check(matches(not(isDisplayed())));

希望这有帮助。

答案 2 :(得分:0)

not(isDisplayed)并不完美,因为该视图可能显示在ScrollView中但在屏幕下方。

简单检查view.getVisibility() != View.GONE也不是100%的解决方案。如果视图父项是隐藏的,则视图实际上是隐藏的,因此测试应通过该方案。

我建议检查视图及其父级是否可见:

fun isNotPresented(): ViewAssertion = object : ViewAssertion {
    override fun check(view: View?, noViewFoundException: NoMatchingViewException?) {
        if (view != null) {
            if (view.visibility != View.VISIBLE) {
                return
            }
            var searchView: View = view
            while (searchView.parent != null && searchView.parent is View) {
                searchView = searchView.parent as View
                if (searchView.visibility != View.VISIBLE) {
                    return
                }
            }
            assertThat<Boolean>(
                "View is present in the hierarchy and it is visible" + HumanReadables.describe(view),
                true,
                `is`(false)
            )
        }
    }
}