Jua*_*iaz 2 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();
}
});
Run Code Online (Sandbox Code Playgroud)
当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));
}
Run Code Online (Sandbox Code Playgroud)
当然,测试失败是因为执行onGlobalLayout该assertThat方法时没有机会运行。
有什么想法吗?
尝试这个:
shadowOf(view.getViewTreeObserver()).fireOnGlobalLayoutListeners();
Run Code Online (Sandbox Code Playgroud)