How to test Paging 3 for Android paging implementation
Written by Mohamed Gamal
Paging 3 is one of the best libraries for pagination — it gives you all you need to implement paging with the lowest efforts and get your data from different data sources (API/local database).
But it's also a tricky one for some reasons:
If you have a listing view without pagination, it's not easy to migrate your old codebase to Paging 3 — some architectural modifications are needed!
Which parts of the code will get affected? Mmmmm - here's a good question, for sure data layer won't be, but Repository will change a little bit with having the new class PagingSource
How to test the PagingSource?!!
Here I get reviews from some API -> getReviews()
Here’s an example for this API response ->
This class is the paging source used to deal with pagination using Paging 3 library:
As you notice here:
No need to have your own Result class for handling responses and helping make a generic error-handling approach, as Paging 3 already runs this by having LoadResult sealed class that takes care of this.
Pass null value to nextKey if there's no next page to be loaded and to prevKey if there's no previous page.
So 3 interesting things here are tricky to be tested, Error Handling, offset and returned data, and one thing to keep in mind load function is a suspend one.
To call this source, I prefer to call it to throw a repo instead of calling it directly from the view model, so I created this repo:
So, how can you test this PagingSource? As mentioned above, the key to identifying expectedResult is LoadResult, and the key to firing the event is LoadParams. LoadParams is a sealed class which is used for the loading request - it has 3 types:
Refresh is used for the initial load or refresh.
Append to load a data page and append it to the end of the list.
Prepend to load a data page and prepend it to the start of the list.
Using this info, here's an example of how you can test ReviewsPagingSource:
It starts with the class initialisation - I stubbed the response here with a limit of only 1 item per load - don't use more for testing logic.
The expected result here should be of type Error with the same exception thrown while calling the API.
Test refresh functionality:
The expected result should be the mapped reviews + nextKey value should be 1, and prevKey value should be null as it's just the first page is loaded.
Test append functionality:
The expected result should be the mapped reviews + nextKey value should be 2, and the prevKey value should be 1 as the 2nd page is loaded.
Test prepend functionality:
The expected result should be the mapped reviews + nextKey value should be 1, and prevKey value should be null as it's just the first page is loaded again.
Enjoy analysing the code - for any questions, don't hesitate to ask me.