This article describes customizing Espresso's matchers through BoundedMatcher.
Overview
Android provides the BoundedMatcher class for creating View-specific Espresso matchers.
For details, please go to: https://developer.android.com/training/testing/espresso/lists.html
Example
Here is a custom matcher for checking EditText hint text:
First you need to create the Matchers class in the src/androidTest/java directory.
/**
* Created by lulu on 2018/3/10.
* 自定义的 View 匹配器
*/
public class Matchers {
public static Matcher<View> withItemHint(final String itemHintText) {
checkArgument(!(itemHintText.equals(null)));
return withItemHint(is(itemHintText));
}
public static Matcher<View> withItemHint(final Matcher<String> matcherText) {
// 如果传入非法的 matcher 需提前处理
checkNotNull(matcherText);
return new BoundedMatcher<View, EditText>(EditText.class) {
@Override
public void describeTo(Description description) {
description.appendText("该 EditText 的 Hint 为: " + matcherText);
}
@Override
protected boolean matchesSafely(EditText item) {
return matcherText.matches(item.getHint().toString());
}
};
}
}
Use the Matchers class you just created with the following code.
// more
import static com.lulu.androidtestdemo.espresso.custom_matcher.Matchers.withItemHint;
/**
* Created by lulu on 2018/3/10.
* 测试自定义匹配器
*/
@RunWith(AndroidJUnit4.class)
public class TestCustomMatcher {
@Rule
public ActivityTestRule<EspressoTest1Activity> mRule =
new ActivityTestRule<EspressoTest1Activity>(EspressoTest1Activity.class);
@Test
public void testEditHintDisplay() throws Exception {
onView(withId(R.id.inputField)).check(matches(withItemHint("this is a hint")));
}
}