Roboletric - 测试onClick到自定义适配器元素

时间:2016-04-12 16:14:28

标签: android robolectric custom-adapter

我正在使用Roboletric,我想测试onClick到" viewHolder.cardView"元件。

这是我的自定义适配器(有两个元素)。我已经构建了我的列表和适配器,但是如何使用roboletric测试onClick事件?

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
   SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_TIME_FORMAT, Locale.getDefault());

     if (position < mMessageList.size()) {

        ItemHolder viewHolder;

        if (convertView == null) {
           convertView =   LayoutInflater.from(getContext())
                       .inflate(R.layout.item_list, parent, false);
           viewHolder = new ItemHolder();
           viewHolder.cardView = (RelativeLayout) convertView.findViewById(R.id.clickable_area);

            viewHolder.txtDate = (TextView)    convertView.findViewById(R.id.message_date);

            convertView.setTag(viewHolder);
            } else {
              viewHolder = (ItemHolder) convertView.getTag();
            }

            final ItemModel item = mMessageList.get(position);

            if (item != null) {
              viewHolder.id = item.getId();
              if (item.getTimestamp() != null){
                          viewHolder.txtDate.setText(dateFormat.format(item.getTimestamp()));
             }

             viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {
                      addSelection();
                  }
              });

       viewHolder.cardView.setOnLongClickListener(new View.OnLongClickListener() {
                  @Override
                   public boolean onLongClick(View view) {
                      return true;
                    }
                  });

                  viewHolder.cardView.setSelected(item.isSelected());
                }
            }
            return convertView;
        }
     static class ItemHolder {
          protected RelativeLayout cardView;
          protected TextView txtDate;
     }

1 个答案:

答案 0 :(得分:0)

以下是我们的相似之处:

SiteAdapter.ViewHolder viewHolder = adapter.onCreateViewHolder(viewGroup, -1);
adapter.setSites(SITES);
adapter.bindViewHolder(viewHolder, 0);

viewHolder.rowLayout.performClick();

verify(busMock).send(selectedEventCaptor.capture());

assertThat(selectedEventCaptor.getValue().getSite()).isEqualTo(SITES.get(0));

其中:

@Captor
private ArgumentCaptor<SiteSelectedEvent> selectedEventCaptor;

@Mock
private EventBus busMock;

private static final List<Site> SITES =
  Arrays.asList(new Site("1", "Test 1", new Links("one", "two")),
                new Site("2", "Test 2", new Links("three", "four")));