ArrayAdapter - 在测试中未调用的filter()方法

时间:2014-02-15 16:12:45

标签: android unit-testing

我尝试对包含过滤的自定义ArrayAdapter进行单元测试。当我在其过滤器上调用方法filter()时 - 它似乎在处理过程中被中断:有时n_filtered = 1显示在日志中,有时只有started filtering有时performFiltering()似乎根本没有调用方法。

我对Android测试很陌生,所以不知道可能是什么原因。某种同步问题?我使用的是正确的测试基类吗?

以下是我的适配器类的片段:

public class PhraseEntryArrayAdapter extends ArrayAdapter<PhraseEntry> implements
        Filterable, SectionIndexer {

    private Language sessionLanguage = null;

    public void setSessionLanguage(Language sessionLanguage) {
        Log.d("test", "filtLang");
        this.sessionLanguage = sessionLanguage;
        getFilter().filter(lastFilterSeq);
    }

    @Override
    public Filter getFilter() {
        if (filter == null) {
            filter = new PhraseLangBFilter();
        }

        return filter;
    }

    private class PhraseLangBFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            Log.d("test", "started filtering");

            FilterResults results = new FilterResults();

            List<PhraseEntry> filt = new ArrayList<PhraseEntry>();
            List<PhraseEntry> items = new ArrayList<PhraseEntry>();

            synchronized (this) {
                items.addAll(objects);
            }

            for (PhraseEntry pe : items) {
                (...)
                if (isOk) {
                    filt.add(pe);
                }
            }

            Log.d("test", "n_filtered = " + filt.size());

            results.count = filt.size();
            results.values = filt;
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {
            (...)
        }
    }

    private PhraseLangBFilter filter;
    private List<PhraseEntry> filtered;
    private final List<PhraseEntry> objects;
    private final List<PhraseEntry> modelList;

    public PhraseEntryArrayAdapter(Context context, List<PhraseEntry> objects) {
        super(context, R.layout.dictionary_entry, objects);

        modelList = objects;
        this.objects = new ArrayList<PhraseEntry>(objects);
        filtered = new ArrayList<PhraseEntry>(objects);
    }

    (...)
}

这是我的简单测试:

public class PhraseEntryArrayAdapterTest extends AndroidTestCase {

    private PhraseEntryArrayAdapter adapter;
    private List<PhraseEntry> dictionary = null;

    public PhraseEntryArrayAdapterTest() {
        super();
    }

    public void setUp() throws Exception {
        super.setUp();
        dictionary = generatePhrases(); // create a list with some data
        adapter = new PhraseEntryArrayAdapter(getContext(), dictionary);
    }

    public void testFilterEmpty() throws Exception {
        adapter.setSessionLanguage(Language.RU);
        assertEquals("wrong numer of items", 1, adapter.getCount());
    }
}

0 个答案:

没有答案