使用Robolectric测试可过滤的适配器

时间:2014-08-01 14:34:00

标签: android robolectric

我为ListView安装了一个适配器,并希望使用Robolectric测试过滤。它不起作用。

java.lang.AssertionError: 
Expected :1
Actual   :2

Robolectric测试:

package com.myapp.test;

import com.myapp.FooAdapter;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import java.util.ArrayList;

@RunWith(RobolectricTestRunner.class)
public class FooAdapterTest {

    @Test
    public void testAdapterCanFilter() {
        ArrayList<String> items = new ArrayList<String>();
        items.add("Keep this");
        items.add("Filtered out");
        FooAdapter adapter = new FooAdapter(items);
        adapter.getFilter().filter("Keep this");
        Assert.assertEquals(1, adapter.getCount());
    }

}

实现:

package com.myapp;

import android.widget.Adapter;
import android.widget.Filter;
import android.widget.Filterable;
import java.util.ArrayList;

public class FooAdapter implements Filterable, Adapter {

    private Filter filter;
    private ArrayList<String> items;

    public FooAdapter(ArrayList<String> items) {
        this.items = items;
    }

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

    @Override
    public int getCount() {
        return items.size();
    }

    // some code omitted ...

    private class MyFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            if (constraint == null || constraint.length() == 0) {
                results.values = items;
                results.count = items.size();
            } else {
                ArrayList<String> filteredItems = new ArrayList<String>();
                for (String item : items) {
                    if (item.equals(constraint)) {
                        filteredItems.add(item);
                    }
                }
                results.values = filteredItems;
                results.count = filteredItems.size();
            }
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            items = (ArrayList<String>) results.values;
        }

    }
}

似乎永远不会调用performFilteringpublishResults

任何帮助表示赞赏!感谢。

1 个答案:

答案 0 :(得分:0)

在后台线程上调用performFilteringpublishResults。 不要直接调用adapter.getFilter().filter(""),而是使用过滤器上的反射调用performFilteringpublishResults方法。