微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用异步过滤测试自定义ArrayAdapter

如何解决使用异步过滤测试自定义ArrayAdapter

我制作了一个自定义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 举报,一经查实,本站将立刻删除。