我正在使用RecyclerView
为Robolectric
个项目编写测试用例。
在调用recyclerView.measure(0,0)
时面对NullPointerException
,因为RecyclerView
已应用RecyclerView.ItemDecoration
,但RecyclerView
与RecyclerView.ItemDecoration
无关。
异常日志:
java.lang.NullPointerException
at ui.adapters.DividerItemDecoration.getItemOffsets(DividerItemDecoration.java:119)
at android.support.v7.widget.RecyclerView$ItemDecoration.getItemOffsets(RecyclerView.java:8662)
在DividerItemDecoration.java
的第119行放置了评论,此处mDivider
变为NULL
,它是从构造函数初始化的。
@Override
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());//Line:119
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
}
}
构造
public DividerItemDecoration(Context context, int orientation) {
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
setOrientation(orientation);
}
ATTRS
private static final int[] ATTRS = new int[]{
android.R.attr.listDivider
};
请提前告知我如何编写RecyclerView
RecyclerView.ItemDecoration
的测试用例,并提前感谢。
解:
最后,我通过为Shadow
创建RecyclerView
类来解决此问题,如下面的代码所述,并遵循基本的阴影映射逻辑,
RecyclerViewShadow.java
@Implements(RecyclerView.class)
public class RecyclerViewShadow extends ShadowViewGroup {
@Implementation
public void addItemDecoration(RecyclerView.ItemDecoration decor, int index) {
}
}