Adam Hurwitz
1 min readJun 15, 2020

--

This is a great practical guide to unit tests for Room database Eyal Guthmann! I did not know setTransactionExecutor and setQueryExecutor existed. These would be useful to have in the Android documentation, Test and debug your database.

There is an issue I discovered with testing Room database queries for a PagedList. Have you worked with tests querying for PagedLists? If so, I’d love to know the strategy taken. Also, this can be ran on the JVM for a local unit test too.

Querying PagedList

One workaround was required in order to test querying for a PagedList from a Dao. The query needs to explicitly call Dispatchers.IO in the unit test.

There is an issue with threading when making a query for a PagedList returning DataSource.Factory<Int, SomeData>, as outlined in this StackOverflow post. The problem is that a suspend function cannot be used, therefore the test threading attempts to run on the main thread without suspend, causing a main thread error.

If the PagedList query in the Dao is refactored with suspend there is a compiler error.

error: Not sure how to convert a Cursor to this method’s return type (androidx.paging.DataSource.Factory<{SomeDataClassPathHere}>).

Workaround

Local Unit Test

Context can be created with Robolectric for a local unit test in order to build the database. See: Create Context with Robolectric in a local unit test.

--

--

Adam Hurwitz
Adam Hurwitz

Written by Adam Hurwitz

An account about nothing | Researcher and product consultant

No responses yet