如何使用Android Espresso测试TextInputLayout值(提示,错误等)?

Ely*_*lye 20 android android-layout android-espresso

如果我的TextInputLayout观点有特定提示,我正在尝试使用Espresso进行测试.我使用了如下代码:

Espresso.onView(ViewMatchers.withId(R.id.edit_text_email))
    .check(ViewAssertions.matches(
        ViewMatchers.withHint(R.string.edit_text_email_hint)))
Run Code Online (Sandbox Code Playgroud)

这适用于普通EditText视图,不包含在内TextInputLayout.然而,当它环绕时,它不再有效.

我尝试使用Android Espresso的解决方案- 如何检查EditText提示?,但它仍然无法正常工作.

我还调查了:https://code.google.com/p/android/issues/detail?id = 191261报告了这个问题,它说通过指向当前withHint代码来解决方法非常简单,但我不能让它工作.

有什么想法来解决这个问题?

pio*_*543 35

这是我的自定义匹配器:

public static Matcher<View> hasTextInputLayoutHintText(final String expectedErrorText) {
        return new TypeSafeMatcher<View>() {

            @Override
            public boolean matchesSafely(View view) {
                if (!(view instanceof TextInputLayout)) {
                    return false;
                }

                CharSequence error = ((TextInputLayout) view).getHint();

                if (error == null) {
                    return false;
                }

                String hint = error.toString();

                return expectedErrorText.equals(hint);
            }

            @Override
            public void describeTo(Description description) {
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是如何使用:

@RunWith(AndroidJUnit4.class)
public class MainActivityTest {

    @Rule
    public ActivityTestRule<MainActivity> mRule = new ActivityTestRule<>(MainActivity.class);

    @Test
    public void testMyApp() {
        onView(withId(R.id.textInputLayout)).check
                (matches(hasTextInputLayoutErrorText(mRule.getActivity().getString(R.string
                        .app_name))));

    }
Run Code Online (Sandbox Code Playgroud)

如果您想查询errorTextTextInputLayout,改变这一行:

     CharSequence error = ((TextInputLayout) view).getHint();
Run Code Online (Sandbox Code Playgroud)

     CharSequence error = ((TextInputLayout) view).getError();
Run Code Online (Sandbox Code Playgroud)

希望它会有所帮助


Phi*_*hil 19

kotlin 版本的 piotrek1543 的回答:

fun hasTextInputLayoutHintText(expectedErrorText: String): Matcher<View> = object : TypeSafeMatcher<View>() {

    override fun describeTo(description: Description?) { }

    override fun matchesSafely(item: View?): Boolean {
        if (item !is TextInputLayout) return false
        val error = item.hint ?: return false
        val hint = error.toString()
        return expectedErrorText == hint
    }
}
Run Code Online (Sandbox Code Playgroud)