简体   繁体   English

如何使用Robolectric测试异步代码

[英]How to test asynchronous code with Robolectric

I have an activity that presents the user with a list of products inside a HorizontalScrollView . 我有一个活动,向用户展示HorizontalScrollView内的产品列表。 I'm using Robolectric to test if the scroll view shows arrows when the list of products is long. 我正在使用Robolectric测试产品列表较长时滚动视图是否显示箭头。

In my Activity I register a OnGlobalLayoutListener like this: 在我的活动中,我像这样注册一个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();
    }
});

This listener is called when the productsScrollView view hierarchy has changed (ie. I've added some subviews to it). productsScrollView视图层次结构更改时(即,我已经向其中添加了一些子视图),将调用此侦听器。 I run the application and all works perfectly. 我运行该应用程序,并且一切正常。

The problem is that I don't know how to test that the hideShowArrowsAsNeeded method do its job. 问题是我不知道如何测试hideShowArrowsAsNeeded方法是否能完成工作。 In my Robolectric test I have this: 在我的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));
}

Of course the test fails because onGlobalLayout didn't have the chance to run when the assertThat method is executed. 当然测试会失败,因为在执行assertThat方法时onGlobalLayout没有运行的机会。

Any thoughts? 有什么想法吗?

尝试这个:

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

As of Roboelectric 4.0, ShadowViewTreeObserver is no more. 从Roboelectric 4.0开始,ShadowViewTreeObserver不再可用。

But you should just be able to do something like: 但是您应该只能执行以下操作:

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

productScrollView?.viewTreeObserver?.dispatchOnGlobalLayout()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM