创建自定义的Espresso匹配器
2018-04-14 本文已影响9人
changer0
本篇讲述通过BoundedMatcher 自定义了Espresso的匹配器.
概述
Android 提供了 BoundedMatcher 类用来创建针对特定 View 的 Espresso 匹配器.
详细内容请移步 : https://developer.android.com/training/testing/espresso/lists.html
示例
下面是一个关于检查 EditText hint 文本的自定义匹配器:
首先你需要在 src/androidTest/java 目录下创建 Matchers 类.
/**
* 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());
}
};
}
}
通过下面代码使用你刚才创建 Matchers 类.
// 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")));
}
}
敲行代码再睡觉