选择espresso作为Android UI的测试,是因为宣传者说Google的很多APP是用的这个框架,另外宣称它的testrunner比较快,网上有人对比了robotium和espresso的执行速度,结果是espresso比较快。这里使用Google默认的模拟器,速度比较慢(使用HAXM加速后稍微快了一点),APP本身(可能是宿主机性能的原因)反应比较慢,因此速度是选择宣称不用wait的espresso的原因。但是使用中也出现了许多问题,UI测试主要是查找元素,能不能快速准确的查找到指定元素并模拟用户操作是非常重要的。现在发现espresso使用的hamcrest match去查找元素,由于初涉android开发,对hamcrest的使用也不熟悉,非常痛苦,偶尔要自己写matcher和action。现在使用的是espresso 1.1。现将遇到的查找元素的sample总结如下:
查找弹出的对话框并操作:
onView(withText("Cancle"))
.inRoot(withDecorView(not(is(getActivity().getWindow().getDecorView()))))
.perform(doubleClick());
上下拖动:
public static ViewAction swipeDown() {
return new GeneralSwipeAction(Swipe.FAST, GeneralLocation.TOP_CENTER,
GeneralLocation.BOTTOM_CENTER, Press.FINGER);
}
public static ViewAction swipeUp() {
return new GeneralSwipeAction(Swipe.FAST, GeneralLocation.BOTTOM_CENTER,
GeneralLocation.TOP_CENTER, Press.FINGER);
}
点击第一个子元素:
public static Matcher<View> firstChildOf(final Matcher<View> parentMatcher) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("with first child view of type parentMatcher");
}
@Override
public boolean matchesSafely(View view) {
if (!(view.getParent() instanceof ViewGroup)) {
return parentMatcher.matches(view.getParent());
}
ViewGroup group = (ViewGroup) view.getParent();
return parentMatcher.matches(view.getParent()) && group.getChildAt(0).equals(view);
}
};
}