How to test TextInputLayout values (hint, error, etc.) using Android Espresso?
Here's my custom matcher:
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) {
}
};
}
}
and here's how to use:
@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))));
}
If you would like to check errorText
of TextInputLayout
, change this line:
CharSequence error = ((TextInputLayout) view).getHint();
with
CharSequence error = ((TextInputLayout) view).getError();
Hope it will help
Kotlin version of piotrek1543's answer:
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
}
}