我为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;
}
}
}
似乎永远不会调用performFiltering
和publishResults
。
任何帮助表示赞赏!感谢。
答案 0 :(得分:0)
在后台线程上调用performFiltering
和publishResults
。
不要直接调用adapter.getFilter().filter("")
,而是使用过滤器上的反射调用performFiltering
和publishResults
方法。