Cor*_*Roy 8 android listview android-espresso
查看和断言listview是android espresso的预期大小的最佳方法是什么?
我写了这个匹配器,但不太清楚如何将它集成到测试中.
public static Matcher<View> withListSize (final int size) {
return new TypeSafeMatcher<View> () {
@Override public boolean matchesSafely (final View view) {
return ((ListView) view).getChildCount () == size;
}
@Override public void describeTo (final Description description) {
description.appendText ("ListView should have " + size + " items");
}
};
}
Run Code Online (Sandbox Code Playgroud)
Cor*_*Roy 25
想出这个.
class Matchers {
public static Matcher<View> withListSize (final int size) {
return new TypeSafeMatcher<View> () {
@Override public boolean matchesSafely (final View view) {
return ((ListView) view).getCount () == size;
}
@Override public void describeTo (final Description description) {
description.appendText ("ListView should have " + size + " items");
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
如果期望列表中的一个项目,请将其放在实际的测试脚本中.
onView (withId (android.R.id.list)).check (ViewAssertions.matches (Matchers.withListSize (1)));
Run Code Online (Sandbox Code Playgroud)
使用espresso在列表中获取项目数有两种不同的方法:第一种是上面提到的@CoryRoy - 使用TypeSafeMatcher,另一种是使用BoundedMatcher.
因为@CoryRoy已经展示了如何断言它,在这里我想告诉如何使用不同的匹配器获取(返回)数字.
public class CountHelper {
private static int count;
public static int getCountFromListUsingTypeSafeMatcher(@IdRes int listViewId) {
count = 0;
Matcher matcher = new TypeSafeMatcher<View>() {
@Override
protected boolean matchesSafely(View item) {
count = ((ListView) item).getCount();
return true;
}
@Override
public void describeTo(Description description) {
}
};
onView(withId(listViewId)).check(matches(matcher));
int result = count;
count = 0;
return result;
}
public static int getCountFromListUsingBoundedMatcher(@IdRes int listViewId) {
count = 0;
Matcher<Object> matcher = new BoundedMatcher<Object, String>(String.class) {
@Override
protected boolean matchesSafely(String item) {
count += 1;
return true;
}
@Override
public void describeTo(Description description) {
}
};
try {
// do a nonsense operation with no impact
// because ViewMatchers would only start matching when action is performed on DataInteraction
onData(matcher).inAdapterView(withId(listViewId)).perform(typeText(""));
} catch (Exception e) {
}
int result = count;
count = 0;
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
还要提一下你应该用ListView#getCount()而不是ListView#getChildCount():
getCount()- 适配器拥有的数据项数量,可能大于可见视图的数量.getChildCount()- ViewGroup中可以由ViewGroup重用的子节点数.| 归档时间: |
|
| 查看次数: |
6814 次 |
| 最近记录: |