使用getActivity()
方法ActivityTestRule。
您将能够使用findViewById()
(如在任何其他上下文中)和处理 RecyclerView实例。
例子:
@RunWith(AndroidJUnit4.class)
public class RandomBehaviorTest {
//This rule provides functional testing of a single activity.
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule<>(MainActivity.class);
@Test
public void clickRandomItem() {
//Magic happening
int x = getRandomRecyclerPosition(R.id.a_main_recycler);
onView(withId(R.id.a_main_recycler))
.perform(RecyclerViewActions
.actionOnItemAtPosition(x, click()));
}
private int getRandomRecyclerPosition(int recyclerId) {
Random ran = new Random();
//Get the actual drawn RecyclerView
RecyclerView recyclerView = (RecyclerView) mActivityRule
.getActivity().findViewById(recyclerId);
//If the RecyclerView exists, get the item count from the adapter
int n = (recyclerView == null)
? 1
: recyclerView.getAdapter().getItemCount();
//Return a random number from 0 (inclusive) to adapter.itemCount() (exclusive)
return ran.nextInt(n);
}
}
在您的例子recyclerView总是为空 – Mike