Test your Paging implementation (Views)

Concepts and Jetpack Compose implementation

Implementing the Paging library in your app should be paired with a robust testing strategy. You should test data loading components such as PagingSource and RemoteMediator to ensure that they work as expected. You should also write end-to-end tests to verify that all of the components in your Paging implementation work correctly together without unexpected side effects.

This guide explains how to test the Paging library in the data layer of your app as well as how to write end-to-end tests for your entire Paging implementation.

Data layer tests

Write unit tests for the components in your data layer to ensure that they load the data from your data sources appropriately. Provide fake versions of dependencies to verify that the components being tested function correctly in isolation. One of the components that you need to test in the repository layer is the RemoteMediator.

RemoteMediator tests

The goal of the RemoteMediator unit tests is to verify that the load() function returns the correct MediatorResult. Tests for side effects, such as data being inserted into the database, are better suited for integration tests.

The first step is to determine what dependencies your RemoteMediator implementation needs. The following example demonstrates a RemoteMediator implementation that requires a Room database, a Retrofit interface, and a search string:

Java (RxJava)

public class PageKeyedRemoteMediator
  extends RxRemoteMediator<Integer, RedditPost> {

  @NonNull
  private RedditDb db;
  @NonNull
  private RedditPostDao postDao;
  @NonNull
  private SubredditRemoteKeyDao remoteKeyDao;
  @NonNull
  private RedditApi redditApi;
  @NonNull
  private String subredditName;

  public PageKeyedRemoteMediator(
    @NonNull RedditDb db,
    @NonNull RedditApi redditApi,
    @NonNull String subredditName
    ) {
      this.db = db;
      this.postDao = db.posts();
      this.remoteKeyDao = db.remoteKeys();
      this.redditApi = redditApi;
      this.subredditName = subredditName;
      ...
    }
  }

Java (Guava/LiveData)

public class PageKeyedRemoteMediator
  extends ListenableFutureRemoteMediator<Integer, RedditPost> {

  @NonNull
  private RedditDb db;
  @NonNull
  private RedditPostDao postDao;
  @NonNull
  private SubredditRemoteKeyDao remoteKeyDao;
  @NonNull
  private RedditApi redditApi;
  @NonNull
  private String subredditName;
  @NonNull
  private Executor bgExecutor;

  public PageKeyedRemoteMediator(
    @NonNull RedditDb db,