Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing RecyclerView Adapters

I have a base RecyclerViewAdapter I want to test in isolation from my various child classes. How do I do this in isolation? I tried creating a slimmed down vanilla Activity in my test class, and using ActivityTestRule to launch it, but unfortunately the testing framework seems to want to launch activities that live in the actual app and not the test app. I don't want to resort to using Robolectric for this, since our team is committed to instrumentation testing using Espresso. What I really want to test is the behavior of the various notify methods in the adapter, since I'm seeing crashes around

android.support.v7.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition

like image 356
Christopher Perry Avatar asked Sep 05 '26 09:09

Christopher Perry


1 Answers

I ended up resolving this by adding a dummy activity in the debug folder, then in my test code manually adding a RecyclerView to the Activity and then setting the adapter on it that I want to test in isolation. When the app compiles the manifest merger will merge any activities declared in the AndroidManifest.xml that live in the debug folder.

Here's my test setup code:

@RunWith(AndroidJUnit4.class)
public class MyRecyclerViewAdapterTest {

    private MyRecyclerViewAdapter adapter;
    private RecyclerView recyclerView;

    @Rule
    public ActivityTestRule<DummyActivity> activityTestRule =
        new ActivityTestRule<>(DummyActivity.class, true, false);

    @Rule
    public UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();

    @Before
    public void setup() throws Throwable {
        final DummyActivity activity = activityTestRule.launchActivity(null);

        uiThreadTestRule.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter = new MyRecyclerViewAdapter(activity);
                recyclerView = new RecyclerView(activity);
                recyclerView.setId(R.id.recycler_view);
                activity.setContentView(recyclerView);
                recyclerView.setLayoutManager(new LinearLayoutManager(activity));
                recyclerView.setAdapter(adapter);
            }
        });
    }
}

and declared the dummy Activity in /src/debug/AndroidManifest.xml:

<activity android:name="com.example.DummyActivity" />

The dummy Activity is simply:

// Dummy Activity for testing
public class DummyActivity extends Activity {
}
like image 105
Christopher Perry Avatar answered Sep 07 '26 02:09

Christopher Perry