如何在Espresso测试中获取输入类型的edittext?

时间:2018-01-23 06:10:39

标签: android unit-testing android-espresso

我的密码button中有一个切换editText,这使得它的输入类型可以是文本或密码,具体取决于检查的内容。我可以执行输入并单击切换按钮,但我不确定espresso matcher功能中的ViewAssertion应该是哪个。

我的代码如下所示。

@Test
    public void checkToggleButton(){
        String password="anuran123";

        onView(withId(R.id.passET)).perform(typeText(password), closeSoftKeyboard());

        onView(withId(R.id.visibilityToggle)).perform(click());

        onView(withId(R.id.passET)).check(matches(allOf(/*NOT SURE WHAT TO DO HERE AS isDiplayed() won't work here.*/)))
    }

3 个答案:

答案 0 :(得分:1)

通过很少的实验,我发现有一个名为withInputType的ViewMactcher可以完成任务。所以最终的代码如下所示

@Test
    public void checkToggleButton(){
        String password="anuran123";

        onView(withId(R.id.passET)).perform(typeText(password), closeSoftKeyboard());

        onView(withId(R.id.visibilityToggle)).perform(click());

        onView(withId(R.id.passET)).check(matches(allOf(withInputType(InputType.TYPE_CLASS_TEXT))));
    }

答案 1 :(得分:0)

请注意,getInputType()等于您想要的类型。

 /**
     * Get the type of the editable content.
     *
     * @see #setInputType(int)
     * @see android.text.InputType
     */
    public int getInputType() {
        return mEditor == null ? EditorInfo.TYPE_NULL : mEditor.mInputType;
    }

答案 2 :(得分:0)

显示/隐藏密码的正确方法是设置TransformationMethod,因此在测试中您可能希望让匹配器检查:

private Matcher<View> isPasswordHidden() {
    return new BoundedMatcher<View, EditText>(EditText.class) {
        @Override
        public void describeTo(Description description) {
            description.appendText("Password is hidden");
        }

        @Override
        public boolean matchesSafely(EditText editText) {
            //returns true if password is hidden
            return editText.getTransformationMethod() instanceof PasswordTransformationMethod;
        }
    };
}

并像这样使用它:

@Test
public void testIsPasswordHidden() throws InterruptedException {
    onView(withId(R.id.password)).perform(typeText("password"));
    onView(withId(R.id.password)).check(matches(isPasswordHidden()));
}