在回收器视图适配器中我有此方法:
public void addGridItemsToView(int position, Tile data) {
tileList.add(position, data);
notifyItemInserted(position);
}
我想对此方法进行单元测试,并检查notifyItemInserted(position)
是否被调用。
这是我的测试课:
public class AdapterTest {
@Mock
private LiveZoneGridAdapter liveZoneGridAdapter;
@Mock
Context context;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void addGridItemsToViewNotifiesParentAndAddsItemToTileList() {
liveZoneGridAdapter = spy(new LiveZoneGridAdapter(context));
doNothing().when((RecyclerView.Adapter) liveZoneGridAdapter).notifyItemInserted(anyInt());
liveZoneGridAdapter.addGridItemsToView(0, new Tile("test", 0, 0, "test"));
Mockito.verify(liveZoneGridAdapter).notifyItemInserted(0);
}
}
如果我运行这样的测试用例,它将在notifyItemInserted
上提供NullPointerException
,即RecyclerView.Adapter
类方法。那么如何测试这种情况?
您正在遇到该错误,因为notifyItemInserted
是最终错误。
Mockito无法模拟/间谍最终方法(尽管有一个孵化功能(。
所以,这条线无法正常工作:
doNothing().when((RecyclerView.Adapter) liveZoneGridAdapter).notifyItemInserted(anyInt());
而不是这样,它将称为真实方法。verify
,也将调用真实方法。
作为解决方法,您应该创建自己的非最佳方法,并使用该方法调用真实的notifyiteminsered。
在您的适配器类中:
public class LiveZoneGridAdapter extends RecyclerView.Adapter {
...
public void addGridItemsToView(int position, Tile data) {
tileList.add(position, data);
internalNotifyItemInserted(position);
}
public void internalNotifyItemInserted(int position) {
notifyItemInserted(position);
}
}
然后在您的测试中:
import android.content.Context;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
public class AdapterTest {
@Mock
Context context;
private LiveZoneGridAdapter liveZoneGridAdapter;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void addGridItemsToViewNotifiesParentAndAddsItemToTileList() {
liveZoneGridAdapter = spy(new LiveZoneGridAdapter(context));
doNothing().when(liveZoneGridAdapter).internalNotifyItemInserted(anyInt());
liveZoneGridAdapter.addGridItemsToView(0, new Tile("test", 0, 0, "test"));
verify(liveZoneGridAdapter).internalNotifyItemInserted(0);
}
}