问题描述
我制作了一个自定义ArrayAdapter并添加了一个自定义过滤器。实现方面很好,所以在SO上还有其他问题。我的问题是关于测试。我无法测试自定义过滤器,因为它是需要访问拥有的ArrayAdapter子类的内部对象。所以我正在测试自定义ArrayAdapter本身:
@RunWith(AndroidJUnit4::class)
@SmallTest
class EquipmentTypeAdapterTest {
@Test
@UiThreadTest
fun filtersBasedOnCategory() {
val typesForCategory = mapOf(
"Category1" to listof("Type 1","Type 2"),"Category2" to listof("Type 3")
)
val adapter = EquipmentTypeAdapter(
InstrumentationRegistry.getInstrumentation().context,typesForCategory
)
// asynchronous call
adapter.filter.filter("Category 2")
// executed before asychronous filtering is actually processed
assertEquals(adapter.count,1)
assertEquals(adapter.getItem(0),"Type 3")
}
}
我的过滤器是android.widget.Filter
的子类。 filter
方法的实现是继承的,并且过滤器的处理是异步的。在此处查看实现:
public abstract class Filter {
// ...
/**
* <p>Starts an asynchronous filtering operation. Calling this method
* cancels all prevIoUs non-executed filtering requests and posts a new
* filtering request that will be executed later.</p>
*
* <p>Upon completion,the listener is notified.</p>
*
* @param constraint the constraint used to filter the data
* @param listener a listener notified upon completion of the operation
*
* @see #filter(CharSequence)
* @see #performFiltering(CharSequence)
* @see #publishResults(CharSequence,android.widget.Filter.FilterResults)
*/
public final void filter(CharSequence constraint,FilterListener listener) {
synchronized (mlock) {
if (mThreadHandler == null) {
HandlerThread thread = new HandlerThread(
THREAD_NAME,android.os.Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mThreadHandler = new RequestHandler(thread.getLooper());
}
final long delay = (mDelayer == null) ? 0 : mDelayer.getPostingDelay(constraint);
Message message = mThreadHandler.obtainMessage(FILTER_TOKEN);
RequestArguments args = new RequestArguments();
// make sure we use an immutable copy of the constraint,so that
// it doesn't change while the filter operation is in progress
args.constraint = constraint != null ? constraint.toString() : null;
args.listener = listener;
message.obj = args;
mThreadHandler.removeMessages(FILTER_TOKEN);
mThreadHandler.removeMessages(FINISH_TOKEN);
mThreadHandler.sendMessageDelayed(message,delay);
}
}
}
因此,断言会在过滤器实际执行之前执行,并且它们会失败。
我想我想在执行过滤器后(调用publishResults
方法之后,延迟断言的处理。并且主线程必须等待所有事情发生才可以完成。我怎样才能做到这一点?还是有区别的方式?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)