[英]How to test asynchronous code with 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));
}
當然測試會失敗,因為在執行assertThat
方法時onGlobalLayout
沒有運行的機會。
有什么想法嗎?
嘗試這個:
shadowOf(view.getViewTreeObserver()).fireOnGlobalLayoutListeners();
從Roboelectric 4.0開始,ShadowViewTreeObserver不再可用。
但是您應該只能執行以下操作:
val productScrollView = fragmentController.get().view?.findViewById<View>(R.id.products_scroll_view)
productScrollView?.viewTreeObserver?.dispatchOnGlobalLayout()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.