我有一个包含ListView的Activity,我试图使用Espresso测试特定条目的存在。使用扩展BaseAdapter的适配器显示ListView的数据。
public class CommentListAdapter extends BaseAdapter {
private static LayoutInflater inflater = null;
Context context;
List<Comment> comments;
public CommentListAdapter(Context context, List<Comment> comments) {
this.context = context;
this.comments = comments;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return comments.size();
}
@Override
public Object getItem(int position) {
return comments.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.comment_row, null);
}
TextView timestamp = (TextView) view.findViewById(R.id.commentTimestamp);
timestamp.setText(new SimpleDateFormat("dd-MM-yyyy hh:mm:ss").format(comments.get(position).getTimeStamp()));
TextView commentText = (TextView) view.findViewById(R.id.commentText);
commentText.setText(comments.get(position).getComment());
return view;
}
}
我需要询问的字段是R.id.commentText字段。查看Espresso的文档我已经看到了一个SimpleAdapter的示例,但是无法看到如何重构它以使用我的CommentAdapter。
我确实想知道是否应该使用SimpleAdapter或ArrayAdapter,但是,由于另一篇文章推荐它,我沿着扩展BaseAdapter的路线走下去。改变我的实现只是为了让Espresso测试运行是错误的,因为编写测试代码并不明显。
拜托,有人可以帮忙吗?
马克
我最终使用的解决方案是使用ArrayAdapter而不是扩展BaseAdapter并创建以下匹配器
public class CommentListAdapterMatchers {
public static Matcher<Object> withContent(String expectedText) {
return withContent(equalTo(expectedText));
}
public static Matcher<Object> withContent(final Matcher<String> expectedObject) {
return new BoundedMatcher<Object, Comment>(Comment.class) {
@Override
public boolean matchesSafely(Comment actualObject) {
return expectedObject.matches(actualObject.getComment());
}
@Override
public void describeTo(Description description) {
description.appendText("with content: " + description);
}
};
}
}
最后我使用了以下onData调用
onData(allOf(is(Comment.class), CommentListAdapterMatchers.withContent("My Comment4"))).check(matches(isDisplayed()));
这适用于我的测试项目,但是当我将其集成到更复杂的布局中时,我需要指定我对使用inAdapterView感兴趣的ListView
onData(allOf(is(Comment.class), CommentListAdapterMatchers.withContent("My Comment4"))).inAdapterView(withId(R.id.commentListView)).check(matches(isDisplayed()));