我有一项活动。它包含片段,这个片段有RecyclerView。一些数据从服务器加载并显示在RecyclerView的第一项内。
我需要为此项设置IdlingResource。因此,当数据将从服务器加载并显示在此项目内时,必须开始测试。
如何为RecyclerView中的项目设置IdlingResource?
答案 0 :(得分:1)
我不确定这是我们的用法,但是它的工作原理...
在您的片段中:
public interface RecyclerViewHaveDataListener {
void recyclerViewHaveData();
}
private RecyclerViewHaveDataListener callbackIdl;
@VisibleForTesting
public void registerOnCallBackIdl(RecyclerViewHaveDataListener callbackIdl){
this.callbackIdl = callbackIdl;
if (adapter.getItemCount() > 0){
this.callbackIdl.recyclerViewHaveData();
this.callbackIdl = null;
}
}
// Use this where you add your datas to your RecyclerView by your adapter
if (callbackIdl != null && adapter.getItemCount() > 0){
callbackIdl.recyclerViewHaveData();
callbackIdl = null;
}
在您的测试包中:
public class RecyclerViewIdlingRes implements IdlingResource, YourFragment.RecyclerViewHaveDataListener {
private String name;
private boolean isIdle;
private volatile ResourceCallback resourceCallback;
public RecyclerViewIdlingRes(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public boolean isIdleNow() {
return isIdle;
}
@Override
public void registerIdleTransitionCallback(ResourceCallback callback) {
this.resourceCallback = callback;
}
@Override
public void recyclerViewHaveData() {
if (resourceCallback == null){
return;
}
isIdle = true;
resourceCallback.onTransitionToIdle();
}
}
在测试中:
@Test
public void itemIsComming(){
RecyclerViewIdlingRes mIdl = new RecyclerViewIdlingRes("idlingRecyclerView");
IdlingRegistry.getInstance().register(mIdl);
Fragment fragment = activity.getSupportFragmentManager().findFragmentById(R.id.activity_main_frame_layout);
if (fragment instanceof YourFragment) {
((YourFragment)fragment).registerOnCallBack(mIdl);
}
onIdle();
IdlingRegistry.getInstance().unregister(mIdl);
// DO YOUR STUFF...
}
答案 1 :(得分:0)
好的方法是实现自己的IdlingResource,它将在数据加载完成后通知Espresso。你可以在这里找到一些例子 - How to use Espresso Idling Resource for network calls