如何使用Robolectric测试异步代码

时间:2014-03-23 16:02:07

标签: android asynchronous robolectric

我有一项活动,向用户显示HorizontalScrollView内的产品列表。我使用Robolectric来测试当产品列表很长时滚动视图是否显示箭头。

在我的活动中,我注册了OnGlobalLayoutListener,如下所示:

ViewTreeObserver vto = productsScrollView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        productsScrollView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        maxScrollX = productsScrollView.getChildAt(0)
            .getMeasuredWidth() - productsScrollView.getMeasuredWidth();

        hideShowArrowsAsNeeded();
    }
});

productsScrollView视图层次结构发生变化时(即我已向其添加了一些子视图),将调用此侦听器。我运行应用程序,一切都很完美。

问题在于我不知道如何测试hideShowArrowsAsNeeded方法是否能够正常工作。在我的Robolectric测试中,我有这个:

@Test
public void testThatAHugeNumberOfProductsShowRightArrow() throws Exception {
    Product product1 = new Product();
    product1.setName("Product1");
    Product product2 = new Product();
    product2.setName("Product2");
    ...

    ArrayList<Product> productsList = new ArrayList<Product>();
    productsList.add(product1);
    productsList.add(product2);
    ...
    activity.drawProducts(productsList); // Here I add the views to the scroll view and onGlobalLayout is eventually called, but now right away

    assertThat(rightArrow.getVisibility(), equalTo(View.VISIBLE));
}

当然测试失败是因为onGlobalLayout在执行assertThat方法时没有机会运行。

有什么想法吗?

2 个答案:

答案 0 :(得分:4)

试试这个:

shadowOf(view.getViewTreeObserver()).fireOnGlobalLayoutListeners();

答案 1 :(得分:0)

从Roboelectric 4.0开始,ShadowViewTreeObserver不再可用。

但是您应该只能执行以下操作:

val productScrollView = fragmentController.get().view?.findViewById<View>(R.id.products_scroll_view)

productScrollView?.viewTreeObserver?.dispatchOnGlobalLayout()