Android:仅为测试添加布局资源到库

时间:2015-05-04 02:30:22

标签: android unit-testing android-testing

在我的公共库代码中,我正在尝试创建一个inflater帮助程序来管理ListView中的多个视图。此代码旨在用于许多项目。

我想为以下代码编写单元测试,因为我需要创建一些xml布局。我知道有可能在Android库中拥有资源,但我希望该布局资源仅用于测试,而不是与它一起发布。下面是我要测试的代码。

public abstract class ListViewItemHolder {

    protected View itemView;

    public View getItemView() {
        return itemView;
    }

    public void initialize(View itemView) {
        this.itemView = itemView;
        copySubviews();
    }

    protected abstract void copySubviews();
}


public class ListViewItemInflater {

    private LayoutInflater inflater;

    private ArrayList<Pair<Integer, Class<ListViewItemHolder>>> viewHolders;

    public ListViewItemInflater(Context context) {
        this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.viewHolders = new ArrayList<Pair<Integer, Class<ListViewItemHolder>>>();
    }

    public <T extends ListViewItemHolder> void registerViewHolder(int resourceId, Class<T> viewHolderClass) {
        viewHolders.add(new Pair<Integer, Class<ListViewItemHolder>>(resourceId, (Class) viewHolderClass));
    }

    public <T extends ListViewItemHolder> T getViewHolder(View itemView, int index) {
        if (itemView == null) {
            Pair<Integer, Class<ListViewItemHolder>> viewInfo = viewHolders.get(index);
            itemView = inflater.inflate(viewInfo.first, null);
            try {
                T viewHolder = (T) viewInfo.second.newInstance();
                viewHolder.initialize(itemView);
                itemView.setTag(viewHolder);
            }
            catch (Exception e) { /* TODO: Still to decide what to do here.  */ }
        }

        return (T) itemView.getTag();
    }
}

ListViewItemInflater注册多个布局ID和视图持有者类,并按需扩展列表项的视图并填充视图持有者类。我试图自动化列表项处理的视图持有者模式。

1 个答案:

答案 0 :(得分:1)