InfiniteScrollListener extends RecyclerView.OnScrollListener { protected boolean canLoadMoreItems() { final int visibleItemsCount = layoutManager.getChildCount(); final int totalItemsCount = layoutManager.getItemCount(); final int pastVisibleItemsCount = layoutManager.findFirstVisibleItemPosition(); final boolean lastItemShown = visibleItemsCount + pastVisibleItemsCount >= totalItemsCount; return lastItemShown && totalItemsCount >= maxItemsPerRequest; } InfiniteScrollListener(int maxItemsPerRequest, LinearLayoutManager layoutManager); @Override void onScrolled(RecyclerView recyclerView, int dx, int dy); abstract void onScrolledToEnd(final int firstVisibleItemPosition);  }
@Test public void testCanLoadMoreItemsLogicIsCorrect() { int visibleItemsCount = 10; int totalItemsCount = 150; int pastVisibleItemsCount = 20; int itemsPerRequest = 100; InfiniteScrollListener listener = createListener(manager, itemsPerRequest); when(manager.getChildCount()).thenReturn(visibleItemsCount); when(manager.getItemCount()).thenReturn(totalItemsCount); when(manager.findFirstVisibleItemPosition()).thenReturn(pastVisibleItemsCount); boolean lastItemShown = visibleItemsCount + pastVisibleItemsCount > totalItemsCount; boolean canLoadMoreItemsExpected = lastItemShown && totalItemsCount >= itemsPerRequest; boolean canLoadMoreItems = listener.canLoadMoreItems(); assertThat(canLoadMoreItems).isEqualTo(canLoadMoreItemsExpected); }
@Test public void testCanLoadMoreItemsShouldBeTrue() { int visibleItemsCount = 10; int totalItemsCount = 20; int pastVisibleItemsCount = 15; int itemsPerRequest = 10; InfiniteScrollListener listener = createListener(manager, itemsPerRequest); when(manager.getChildCount()).thenReturn(visibleItemsCount); when(manager.getItemCount()).thenReturn(totalItemsCount); when(manager.findFirstVisibleItemPosition()).thenReturn(pastVisibleItemsCount); boolean canLoadMoreItems = listener.canLoadMoreItems(); assertThat(canLoadMoreItems).isTrue(); }
@Test public void testCanLoadMoreItemsShouldBeFalse() { int visibleItemsCount = 10; int totalItemsCount = 30; int pastVisibleItemsCount = 15; int itemsPerRequest = 100; InfiniteScrollListener listener = createListener(manager, itemsPerRequest); when(manager.getChildCount()).thenReturn(visibleItemsCount); when(manager.getItemCount()).thenReturn(totalItemsCount); when(manager.findFirstVisibleItemPosition()).thenReturn(pastVisibleItemsCount); boolean canLoadMoreItems = listener.canLoadMoreItems(); assertThat(canLoadMoreItems).isFalse(); }