代码之家  ›  专栏  ›  技术社区  ›  irobotxx

浓缩咖啡:测试文本输入布局密码可见性切换按钮

  •  0
  • irobotxx  · 技术社区  · 7 年前

    好的一天,我正在努力学习浓咖啡,我正在尝试检查TextInputLayout的PasswordVisibilityToggleEnabled按钮是否可见。我知道这个按钮是一个带id的可检查的ImageButton( R.id.text_input_password_toggle) 但不知道怎么把它放进浓咖啡里。

    我试过这样做:

    onView(withId(R.id.passwordTextInputLayout)).check(hasDescendant(withId(R.id.text_input_password_toggle))).check(matches(not(isDisplayed())));
    

    但这不管用。我猜我可能需要使用一个基于StackOverflow上的一些问题的自定义匹配器,但不确定这样做是否正确。

    public static Matcher<View> getPasswordToggleView(final Matcher<View> parentMatcher, int id) {
        return new TypeSafeMatcher<View>() {
            @Override
            protected boolean matchesSafely(View view) {
                if(!(view.getParent() instanceof ViewGroup)) {
                    return parentMatcher.matches(view.getParent());
                }
    
                ViewGroup group = (ViewGroup) view.getParent();
                return  parentMatcher.matches(view.getParent()) && view.getId() == id;
            }
    
            @Override
            public void describeTo(Description description) {
                description.appendText("get View with matching id");
            }
        };
    }
    

    试着像这样使用,但仍然不起作用:

     onView(getPasswordToggleView(withId(R.id.passwordTextInputLayout), R.id.text_input_password_toggle)).check(matches(not(isDisplayed())));
    

    有什么想法吗?

    0 回复  |  直到 7 年前
        1
  •  0
  •   Aaron    7 年前

    在你的代码中:

    onView(withId(R.id.passwordTextInputLayout))
        .check(hasDescendant(withId(R.id.text_input_password_toggle))) // assume you forgot matches(...)
        .check(matches(not(isDisplayed())));
    

    not(isDisplayed)) 在TextInputLayout上执行,而不是它的 CheckableImageButton 如你所料。若要修复此错误,只需将代码重新排列为:

    onView(withId(R.id.passwordTextInputLayout))
        .check(matches(allOf(hasDescendant(withId(R.id.text_input_password_toggle)), not(isDisplayed()))))
    

    或者,如果要为创建自定义匹配器 TextInputLayout ,您可以尝试:

    public static Matcher<View> isPasswordVisibilityToggleEnabled() {
        return new BoundedMatcher<View, TextInputLayout>(TextInputLayout.class) {
    
            @Override public void describeTo(Description description) {
                description.appendText("is password visibility toggle enabled");
            }
    
            @Override protected boolean matchesSafely(TextInputLayout view) {
                return view.isPasswordVisibilityToggleEnabled();
            }
        };
    }
    

    然后您可以将测试代码更改为:

    onView(withId(R.id.passwordTextInputLayout))
        .check(matches(not(isPasswordVisibilityToggleEnabled())))
    

    我想 view.isPasswordVisibilityToggleEnabled()

        2
  •  0
  •   ror    7 年前

    只要你(显然)已经可以使用切换按钮的id,你就可以这样做 onView(withId(R.id.text_input_password_toggle)).check(doesNotExist()) 不显示to check切换按钮。如果 passwordToggleEnabled 是假的。

    doesNotExist android.support.test.espresso.assertion