Issue
The Test - I have an Espresso test suite designed to test some complex decision making with a RecyclerView adapter.
For one test I intend to create a RecyclerView, pass it the adapter under test and then determine that the correct number of children exist, with the correct elements being visible.
The problem - I am testing this in isolation without a specific Activity, which means that the following code never passes, because the RecyclerView never lays out its children:
RecyclerView rv = new RecyclerView(InstrumentationRegistry.getTargetContext());
rv.setAdapter(adap);
assertThat(rv.getChildCount(), is(greaterThan(0)));
I assume I could make this work by creating an empty activity and an empty layout with the RecyclerView in, but i want to avoid creating garbage classes like that.
The Question - Is it possible to get the RecyclerView to function alone like this? Does Espresso have some root view I can access to attach it to?
Solution
As noted by CommonsWare, the way to ensure RecyclerView is ready for testing without an activity is to force layout yourself.
RecyclerView rv = new RecyclerView(InstrumentationRegistry.getTargetContext());
rv.setLayoutManager(new LinearLayoutManager(InstrumentationRegistry.getTargetContext()));
rv.setAdapter(adapter);
rv.measure(View.MeasureSpec.AT_MOST, View.MeasureSpec.AT_MOST);
rv.layout(0,0, 800, 480); //arbitrary sizes
After creating your view in this manner, the child count will no longer be zero
assertThat(rv.getChildCount(), is(greaterThan(0)));
The one caveat to testing the RecyclerView without an Activity is you are unable to perform actions.
onView(...).perform(click());
Without an activity this code will throw a RuntimeException with the message
No activities found. Did you forget to launch the activity by calling getActivity() or startActivitySync or similar?
Answered By - Nick Cardoso
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.