简体   繁体   中英

How to test asynchronous code with Robolectric

I have an activity that presents the user with a list of products inside a HorizontalScrollView . I'm using Robolectric to test if the scroll view shows arrows when the list of products is long.

In my Activity I register a OnGlobalLayoutListener like this:

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). 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. In my Robolectric test I have this:

@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.

Any thoughts?

尝试这个:

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

As of Roboelectric 4.0, ShadowViewTreeObserver is no more.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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